Domanda

I am getting garbage / junk values as output when my program is run and the data displayed.

Why is it so?

Can someone help me to understand how to properly pass by pointers and not get junk values?

This program is about stack creation of struct books type variables.

By default shouldn't the variable bks pass by pointer and change when b is changed?

bks is still storing garbage value.

Here is my code:

#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();
}
È stato utile?

Soluzione

Each time you recursively call main(), you create a new array bk.

The information you entered in the previous invocation of main() is hidden from the new one.

  • To iterate is human; to recurse, divine.

In this context, give up divinity for humanity. Use iteration — in this context it is better.

This is your primary problem; there may also be other off-by-one or other errors.

Altri suggerimenti

push:
if(top==n-1)
        return -1;
main:
top=push(bks,top,10);

top is reset when the stack is full

Edit: And the second problem is main being called again, struct books bks[10] is reset in the next main, it is a recursion. Declare bks as global or go with a while loop instead of recursion.

while (1) {
    getChoices();
    if (exit)
        /* exit from here */
    process();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top