Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Double Pointer to Structure

Tags:

I am trying to work out a double pointer to a structure in C and cannot figure out what is going wrong... The simple source is below:

typedef struct {     int member; } mystruct;  void myfunc(mystruct **data) {     (*data)->member = 1; }  void main(int argc, char *argv[]) {     mystruct **data;      myfunc(data);      printf("member = %d\n", (*data)->member); } 

A similar question was asked here: How to work with pointer to pointer to structure in C? on how to modify a member of a structure through a double pointer. The solution was the syntax (*data)->member = 1; which makes sense. But in my little application here, I receive a seg fault when executing that line. What am I doing wrong?

Thanks

like image 210
linsek Avatar asked Oct 03 '11 17:10

linsek


People also ask

Can you have a pointer to a struct in C?

Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures. Structure in C is a user-defined data type which is used to store heterogeneous data in a contiguous manner.

What is double pointer in data structure?

A pointer is used to store the address of variables. So, when we define a pointer to pointer, the first pointer is used to store the address of the second pointer. Thus it is known as double pointers.

Can you have a double pointer in C?

Whereas pointer to pointer which means a pointer stores the address of another pointer, and this second pointer will be storing the address of the previous or first pointer which is also known as double-pointer in C. Therefore, double pointers are used when we want to store the address of the pointers.


1 Answers

You need to point to something if you are going to dereference a pointer. Try this:

void main(int argc, char *argv) {     mystruct actualThing;     mystruct *pointer = &actualThing;     mystruct **data = &pointer;     myfunc(data);      printf("Member: %d", (*data)->member); } 
like image 180
DwB Avatar answered Oct 12 '22 23:10

DwB