我正在编写一个C程序来实现将元素压入和弹出到堆栈中。我的代码如下

#include <stdio.h>

#define MAX_STACK 10
struct stack_array
{
    int contents[MAX_STACK];
    int top;
};

typedef struct stack_array stack;

void display_stack(stack *head)
{
    int i;
    for (i=0; i<MAX_STACK; i++)
    {
        if (i<=head->top)
            printf(" %d -",(head->contents[i]));
        else
            printf(" N -");
    }
    printf("\n");
}

void push(stack *head, int value)
{
    if (head->top==-1 && MAX_STACK!=0)
    {
        head->contents[0]=value;
        head->top=0;
    }

    else if (((head->top)+1)==MAX_STACK)
        printf("Stack Full\n");

    else
        head->contents[++head->top]=value;
}

void fill_stack(stack *head, int size, char **contents)
{
    int i, value;
    for (i=0; i<size-1; i++)
    {
        value=strtol(contents[i],NULL,10);
        printf("\nPushing %d in to stack\n", value);
        push(head, value);
        display_stack(head);
    }
}

int pop(stack *head)
{
    if (head->top !=-1)
    {
        --head->top;
        return head->contents[head->top+1];
    }

    else
        printf("\nNo more elements in stack left\n");
}

void remove_stack(stack *head)
{
    int i;
    for (i=head->top; i>0; i--)
    {
        printf("\nPopping %d out of the stack:\n",pop(head));
        display_stack(head);
    }
}

void main(int argc, char **argv)
{

    stack head;
    fill_stack(&head, argc, argv+1);
    remove_stack(&head);
}


但是我的输出中有一个奇怪的字符,像这样,


  $ ./stack.o 1 2 3
  
  将1推入堆栈15774463-1-N-N-N-N-N-N-N-N-N-
  
  将2推入堆栈15774463-1-2-N-N-N-N-N-N-N-
  
  将3推入堆栈15774463-1-2-3-N-N-N-N-N-N-
  
  从堆栈中弹出3:15774463-1-2-N-N-N-N-N-N
  -N-
  
  从堆栈中弹出2个:15774463-1-N-N-N-N-N-N-N-N
  -N-
  
  从堆栈中弹出1:15774463-N-N-N-N-N-N-N-N-N
  -N-


现在我不确定15774463是做什么用的。您能帮忙解决为什么显示堆栈数组时出现这样一个数字的原因。

对不起,我英语水平很差,希望您能得到我想要问的。请让我解释一下您是否不明白我的意思。

谢谢。

最佳答案

您没有初始化堆栈。

// Wrong, uninitialized!
stack head;

// Initialized, C99
stack head = { .top = -1 };

// Initialize, for ancient compilers without C99 support.
stack head;
head.top = -1;


在设置它们的值之前,函数范围内的自动变量未初始化。

关于c - C:打印指向数组的指针似乎也会打印垃圾值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24983501/

10-09 04:57