【问题标题】:C program with an array based stack using pointers具有使用指针的基于数组的堆栈的 C 程序
【发布时间】:2019-02-23 22:35:03
【问题描述】:

这是我的代码,它不起作用。有任何想法吗?我不能根据给定的赋值更改主函数或任何函数名称或参数,我只能更改函数的内容。我超级卡住了。任何帮助表示赞赏。我已经在推送功能上运行了 GDB,它似乎工作得很好。但是,打印堆栈函数认为数组的长度为0,这根本没有帮助。非常感谢!

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);
}

【问题讨论】:

  • 您的代码调用了未定义的行为n=arr; return n; 返回 makestack 中自动本地数组的基地址。一旦您从该点开始在代码中的任何位置取消引用现在悬空的指针,轮子就会脱落。而且你正在泄漏内存。相关的,将int * 隐藏在类型别名stack 中可能是这段代码中无用的事情。不要那么做。我怀疑您应该使用包含数组和顶部索引的struct stack,并通过地址传递该事物的实例。
  • typedefs 隐藏指针是对 bug 的邀请。
  • typedef int *stack; 是问题的一部分,还是您的想法?
  • 在 typedef 后面隐藏指针只会增加混乱,不要这样做。

标签: c arrays function pointers stack


【解决方案1】:

你有未定义的行为,因为

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

arrmakestack 的局部变量,一旦控制退出makestack 就会被销毁。因此,您将进一步提及无效内存。

因此将makestack更改为如下。

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

注意:类型定义指针是错误的,避免它。

  typedef int *stack; //bad

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 2013-07-26
    • 2011-02-13
    • 2012-04-21
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    相关资源
    最近更新 更多