【问题标题】:Stack not succeding in pushing a number into it堆栈没有成功将数字推入其中
【发布时间】:2018-05-26 10:16:41
【问题描述】:

我正在尝试制作一个将元素保存在数组中的“桶”,当我访问推送函数时,我想将 x 元素放在该数组中。我不明白为什么数组一直是空的。它为此输入打印:

" /n /n /n 堆栈是空的! 弹出:-9999 \n \n \n \n \n 堆栈是空的! 弹出:-9999 \n \n \n \n \n \n "

#include <stdio.h>
#include <stdlib.h>


typedef struct stivaStack
{
    int arr[10];
    int len;
}stivaStack_t;


void printStiva(stivaStack_t S)
{
    int i;
    for (i=0;i<S.len;i++)
        printf("%d ",S.arr[i]);
    printf("\n");
}

void stivaPush(int x, stivaStack_t S)
{
    if (S.len+1<10)
    {
        int a=S.len;
        S.arr[a]=x;
        S.len=a+1;
    }
    else
    printf("The stack is full can't place %d!\n",x);
}

int stivaPop(stivaStack_t S)
{
    if (S.len>0)
    {
        S.len--;
        return S.arr[S.len];
    }
    else
    {
        printf("The stack is empty!\n");
        return -9999;
    }
}

int main()
{

    stivaStack_t SS;
    SS.len=0;

    stivaPush(102,SS); printStiva(SS);
    stivaPush(25,SS); printStiva(SS);
    stivaPush(9,SS); printStiva(SS);
    printf("Popped: %d\n",stivaPop(SS)); printStiva(SS);
    stivaPush(3,SS); printStiva(SS);
    stivaPush(12,SS); printStiva(SS);
    stivaPush(29,SS); printStiva(SS);
    stivaPush(40,SS); printStiva(SS);
    printf("Popped: %d\n",stivaPop(SS)); printStiva(SS);
    stivaPush(155,SS); printStiva(SS);
    stivaPush(4,SS); printStiva(SS);
    stivaPush(19,SS); printStiva(SS);
    stivaPush(25,SS); printStiva(SS);
    stivaPush(49,SS); printStiva(SS);

    return 0;
}

【问题讨论】:

  • 你必须通过引用而不是值来传递堆栈。例如 void stivaPush(int x, stivaStack_t *S);否则,函数会处理堆栈的副本。
  • 考虑到stivaPush函数中的if (S.len+1
  • @VladfromMoscow 谢谢,这可能是问题之一。我试图改变它,但我现在收到错误消息,说我请求成员 len 不是结构或联合。在我通过引用作为参数传递它之后,我应该如何在函数中访问这些值(len,arr)? S.len 或 *S.len 都不起作用。
  • @VladfromMoscow 我不想使用“通过引用传递”术语,因为 C 实际上并不做引用。
  • @AndreiSold 如果您使用的是指针,则语法会更改,例如 S->len。或 (*S).len

标签: c arrays stack push bucket


【解决方案1】:

这些函数处理堆栈的副本而不是原始堆栈本身。

您必须通过引用函数来传递堆栈。

例如

void stivaPush(int x, stivaStack_t *S)
{
    if (S->len < 10)
        ^^^^^^^^^^^
    {
        int a = S->len;
        S->arr[a]=x;
        S->len=a+1;
    }
    else
    printf("The stack is full can't place %d!\n",x);
}

函数调用可能看起来像

stivaPush(102, &SS); 

当函数发出消息时也是一个坏主意。

上面的函数可以这样定义

int stivaPush( stivaStack_t *S, int x )
{
    int success = S->len < 10;

    if ( success )
    {
        S->arr[len++] = x;
    }

    return success;
}

【讨论】:

    【解决方案2】:

    我不明白为什么数组一直是空的。

    因为你将变量按值传递给函数。我们的意思是,您调用带有变量的函数,在被调用的函数中还有另一个与此内容相同的函数。然后你工作。副本上。函数结束。副本被丢弃。就这样结束了。原来的变量还是一样的。

    如何解决?

    通过传递变量的地址来模拟 C 中的引用传递。好吧,在不使事情复杂化的情况下,理解这一点的简单方法是,而不是传递变量的值,而是传递变量的地址。这里同样,被调用函数中有一个局部变量,其内容与变量地址的内容相同。现在,您可以通过包含地址的变量副本访问地址。您对存储在该地址中的变量进行更改。因此,您所做的更改会保留下来。

    怎么做?

    嗯,它在另一个答案中给出。答案显示了如何使用代码来做到这一点。不重复内容。

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2023-03-27
      • 2017-03-22
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多