Reputation: 1320
Today I had an exam on ponters in C, and there was some questions about double pointers where the following syntax was used
*pointer = &variable;
I don't know if I have done correctly, but can someone explain where will pointer point to and how will the value in variable change? At first I thought it will cause sntax error, but there was no such answer in a test. Thanks in advance
Upvotes: 1
Views: 94
Reputation: 30123
If the pointer is initialized this way:
int *pointer;
int variable = 10;
pointer = malloc(sizeof(int));
*pointer = &variable;
*pointer = &variable
means the address of variable is set as value of the pointee. Since *pointer
is dereferencing so you are basically storing a value not setting a reference.
Upvotes: 0
Reputation: 27664
pointer
is a pointer to a pointer.
Eg,
int var1=42;
int* intptr;
int** ptr2intPtr;
ptr2intptr = &intptr;
//Syntax in question.
*ptr2intptr = &var1;
//Just like *intptr is same as var1, *ptr2intptr is same as intptr
//so the above line will be equivalent to intptr = &var1
//All the three are the same
printf("%d",**ptr2intptr);
printf("%d",*intptr);
printf("%d",var1);
Upvotes: 0
Reputation: 455142
// two int variables.
int var1;
int var2;
// int pointer pointing to var1
int *ptr = &var1;
// pointer to int pointer..pointing to ptr
int **ptr_to_ptr = &ptr;
// now lets make the pointer pointed to by ptr_to_ptr
// point to var2
*ptr_to_ptr = &var2;
// or alternatively you can do:
// ptr = &var2;
Upvotes: 1
Reputation: 318518
Here's an example on how you could use it:
int foo = 123;
int **bar = malloc(sizeof(int *));
*bar = &foo;
Now bar
is a pointer to a pointer to foo. Doesn't make much sense though.
Upvotes: 0