Shiva
Shiva

Reputation: 13

C : Printing a pointer to an array seems to print a junk value also

I am writing a C program to Implement pushing and popping elements in to a stack. My code is below,

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

But there is a strange characters in my output, which comes like this,

$ ./stack.o 1 2 3

Pushing 1 in to stack 15774463 - 1 - N - N - N - N - N - N - N - N -

Pushing 2 in to stack 15774463 - 1 - 2 - N - N - N - N - N - N - N -

Pushing 3 in to stack 15774463 - 1 - 2 - 3 - N - N - N - N - N - N -

Popping 3 out of the stack: 15774463 - 1 - 2 - N - N - N - N - N - N - N -

Popping 2 out of the stack: 15774463 - 1 - N - N - N - N - N - N - N - N -

Popping 1 out of the stack: 15774463 - N - N - N - N - N - N - N - N - N -

Now I am not sure what the 15774463 is for. Could you please help in solving why such a number comes when displaying the array of stack.

Pardon my poor English skills, Hope you get what I wanted to ask. Please ask to me to explain if you don,t understand what I said.

Thank you.

Upvotes: 0

Views: 170

Answers (2)

Dietrich Epp
Dietrich Epp

Reputation: 213258

You didn't initialize the stack.

// Wrong, uninitialized!
stack head;

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

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

Automatic variables in function scope are uninitialized until you set their values.

Upvotes: 1

CRM
CRM

Reputation: 1349

Replace the first line inside main() with this

stack head = NULL;

to initialise stack pointer to NULL at first.

Upvotes: 0

Related Questions