简体   繁体   English

具有指针的基于数组的堆栈的C程序

[英]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. 我已经在push函数上运行了GDB,它似乎运行得很好。 However, the print stack function thinks that the length of the array is 0, which is not helpful at all. 但是,打印堆栈函数认为数组的长度为0,这完全没有帮助。 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 . arrmakestack局部变量,一旦控件退出makestack ,它将被销毁。 Hence you will be referring to invalid memory going further. 因此,您将指的是无效的内存。

Thus change makestack to as below. 因此将makestack更改为如下。

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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