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
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With