简体   繁体   中英

C program with an array based stack using pointers

This is my code and it is not working. Any ideas? I can't change the main function or any of the function names or parameters based on the assignment given I can only change the content of the functions. I'm super stuck. Any help is appreciated. I have run GDB on the push function and it seems to be working great. However, the print stack function thinks that the length of the array is 0, which is not helpful at all. Thanks so much!

typedef int *stack;

void push (stack st, int num)
{
        int len = st[0];
        st[len+1]=num;
        st[0]++;

}
int pop(stack st)
{
        int len = st[0], x;
        x = st[len];
        st[0]--;
        return x;
}
void printstack(stack st)
{
        int i, len= st[0];
        for(i=1;i<=len;i++)
        {
                printf("%d ", st[i]);
        }

}
stack makestack()
{
        stack n;
        int arr[20];
        n = malloc(sizeof(stack));
        arr[0]=0;
        n= arr;
        return n;
}
int main()
{
 stack s;
 stack t;
 s = makestack();
 t = makestack();

 int x;
 push(s, 4);
 push(s, 6);
 push(t, 7);
 push(t, 5);
 printstack(s);
 printstack(t);
 x = pop(s);
 printf("%d popped from s\n", x);
 printstack(s);
 printstack(t);
}

You have undefined behavior because

stack n;
int arr[20];
n = malloc(sizeof(stack));
arr[0]=0;
n= arr;
return n;

arr is local variable to makestack and will be destroyed once control exits makestack . Hence you will be referring to invalid memory going further.

Thus change makestack to as below.

    stack makestack()
    {
            stack n = malloc(sizeof(int)*20);
            n[0]=0;
            return n;
    }

Note: Typedefing the pointer is erroneous avoid it.

  typedef int *stack; //bad

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM