Question:
C programming question with pointers to sturctures?
2009-10-12 22:51:39 UTC
If I declare a structure such as:

struct node
{
int data;
};

and then I declare a pointer to struct node variable such as:

struct node *a;

Then if I try to assign an integer value to a->data

int number = 18;

a->data = number;

I get a segmentation fault, how can I resolve this issue?
Three answers:
gene_frequency
2009-10-13 00:07:25 UTC
No memory was allocated. 'a' is a pointer of type struct node, but it is not a pointer to struct node. There is a huge difference....



struct node

{

int data;

};



struct node *a;

int number = 18;



a = &node; //now a has some (static) memory

a->data = number; //....and you can do this.



//.....or....



a = malloc(sizeof(struct node)); //now a has some dynamic memory

a->data = number; //....and you can do this.



------------------------------



What if you had a significant sized, complex structure?



struct node2

{

int data;

float value;

int array[12];

};



struct node2 *a;



//.... inspect the sizes of these objects:



printf("sizeof(struct node)= %d\n", sizeof(struct node));

printf("sizeof(a)= %d\n", sizeof(a));



When you look at the output of the above, ask yourself, would this next statement allocate the right amount of memory?



struct node *a = malloc(sizeof(a));
Paul
2009-10-13 00:13:35 UTC
You can't just define a pointer to a struct and not allocate the struct itself. Instead you need to do something like this:



struct node

{

....int data;

};



struct node a;



a.data = 42;



If you want to allocate and free nodes dynamically (the most common usage pattern for data structures like linked lists and trees etc) then you need to do something like this:



struct node *a = malloc(sizeof(*a));

a->data = 42;
?
2016-10-21 13:46:55 UTC
A pointer isn't a common variable, it incredibly is a particular variety of variable it is used to save the address of a common variable.it incredibly is used to boost the fee of the device.we are able to accomplish upload,sub on pointer variables.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...