为什么这会给垃圾价值?

时间:2013-08-31 06:29:32

标签: c pass-by-reference garbage

当我的程序运行并显示数据时,我将垃圾/垃圾值作为输出。

为什么会这样?

有人可以帮助我理解如何通过指针正确传递而不是获取垃圾值吗?

这个程序是关于struct books类型变量的堆栈创建。

默认情况下,变量bks不应该通过指针传递并在b更改时更改?

bks仍然存储垃圾值。

这是我的代码:

#include<stdio.h>
#include<stdlib.h>
struct books
{
    int yrpub;
    char name[100],author[50];
};
int top=-1;
int push(struct books b[],int top,int n)
{
    if(top==n-1)
        return -1;
    else
    {
        ++(top);
        printf("Enter books info: \n");
        printf("Enter name: ");
        gets(b[top].name);
        printf("Enter author: ");
        gets(b[top].author);
        printf("Enter Year of publish: ");
        scanf("%d",&b[top].yrpub);
        return top;
    }
}
void display(struct books b[],int top)
{
    int i;
    if(top==-1)
        printf("No books in the stack...");
    for(i=0;i<=top;i++)
    {
        printf("Details of book %d: \n",i+1);
        printf("Name: %s\nAuthor: %s\nYear of publish: %d\n",b[i].name,b[i].author,b[i].yrpub);
    }
    system("pause");
}

int main()
{
    struct books bks[10];
    int ch;
    system("cls");
    printf("Select an option:\n");
    printf("1. Push book\n2. Pop book\n3. Peep book\n4. Display all books info\n5. Exit\n");
    printf("Enter a choice: ");
    scanf("%d",&ch);
    fflush(stdin);
    switch(ch)
    {
    case 1:
        system("cls");
        top=push(bks,top,10);
        break;

    case 4:
        system("cls");
        display(bks,top);
        break;

    case 5:     exit(0);

    default:    printf("\nWrong choice...Please retry.");
        long i,j;
        for(i=0;i<1000000;i++)
            for(j=0;j<100;j++);
    }
    main();
}

2 个答案:

答案 0 :(得分:2)

每次递归调用main()时,都会创建一个新数组bk

您在上一次调用main()时输入的信息对新信息隐藏。

  • 迭代是人;提升,神圣。

在这种情况下,放弃人性的神性。使用迭代 - 在这种情况下它更好。

这是你的主要问题;可能还有其他一个或一个错误。

答案 1 :(得分:0)

push:
if(top==n-1)
        return -1;
main:
top=push(bks,top,10);
当堆栈完整

时,

top被重置

编辑: 第二个问题是再次调用mainstruct books bks[10]在下一个main中重置,它是递归。将bks声明为全局或使用while循环而不是递归。

while (1) {
    getChoices();
    if (exit)
        /* exit from here */
    process();
}
相关问题