-1

program picture

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

struct tree {
    int data;
    struct tree *left, *right;
};

struct queue {
    struct tree **nodeQ = (struct tree**)malloc(sizeof(struct tree*));
    int front;
    int rear;
};
chqrlie
  • 131,814
  • 10
  • 121
  • 189
sam
  • 1

2 Answers2

1

In C you can't initialize structure members inline like you try to do with the nodeQ member.

You need to initialize the member when you create the structure.

So you need to do something like

struct queue q = { malloc(sizeof(struct tree *)), 0, 0 };

or

struct queue *q = malloc(sizeof(struct queue));
q->nodeQ = malloc(sizeof(struct tree *));
q->front = 0;
q->rear = 0;

Note that I do not cast the result of malloc.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

The problem you are having is initializing the structure when you define it. When using struct name_of_struct{...}; You are defining a data type. Due to this you can't give it an inicial value.

struct tree{

     int data;        
     struct tree *left,*right;    

};       


struct queue{

    struct tree ** nodeQ;  
    int front;    
    int rear;    

};    

This should do as a definition, also remember to use indentation and comment your code as this will result in a much more understandable program and you'll actually understand it 2 weeks from now.

Also I think there's actually an error in your code, shouldn't nodeQ be a normal pointer and not a double pointer? If you try to dereference(acess the content referenced by the pointer) twice you'll get a seg fault.

Here's how you should initialize the content of nodeQ supposing its a SINGLE POINTER and in a function I'll initialize it in the main function this time.

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




struct tree{

    int data;        
    struct tree *left,*right;    

};       


struct queue{

    struct tree * nodeQ;
    int front;    
    int rear;    

}; 



int main(void)
{
    struct queue my_queue;
    if(my_queue.nodeQ=malloc(sizeof(struct tree)))
        fprintf(stderr, "Unable to allocate memory for my_queue nodeQ\n");


    return 0;
} 
Mr. Branch
  • 442
  • 2
  • 13