Search code examples
cpointersstructinitializationallocation

Initializing struct in C


OK, this is the definition of the struct:

typedef struct {
   int first;
   int last;
   int count;
   char * Array [50];
} queue;

and I use another function to initialize it

void initialize(queue * ptr){
   ptr=malloc(sizeof(queue));
   ptr->first=0;
   ptr->last=0;
   ptr->count=0;
}

Then I use printf to print out first, last and count. All three should be zero. However, what I actually get is, count is 0 as I expected, but first&last are two very large strange numbers and they change every time I run the program. Can anybody tell me what's wrong here? Thank you.


Solution

  • You are passing your pointer by value. The function changes a copy of the argument it receives, but the caller's pointer is not modified and is probably unintialized.

    You need to change your function to take a queue** and pass the address of the pointer you want to initialize.

    Alternatively you could return a pointer instead of passing it in as an argument. This is a simpler approach.