C:打印指向数组的指针似乎也会打印垃圾值

时间:2014-07-27 17:21:06

标签: c arrays pointers stack

我正在编写一个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 -

     

将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 -

     

从堆栈中弹出1:15774463 - N - N - N - N - N - N - N - N    - N -

现在我不确定15774463的用途。你能帮忙解决为什么在显示堆栈数组时出现这样的数字。

请原谅我糟糕的英语技能,希望你能得到我想要的。如果你不明白我说的话,请让我解释一下。

谢谢。

2 个答案:

答案 0 :(得分:1)

你没有初始化堆栈。

// Wrong, uninitialized!
stack head;

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

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

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

答案 1 :(得分:0)

用{/ p>替换main()内的第一行

stack head = NULL;

首先将堆栈指针初始化为NULL。

相关问题