MrMoog
MrMoog

Reputation: 417

Accessing address of the pointer in a C struct

I have a struct:

struct test {
   int **x;
}

How can I access address of the pointer x?

SOLVED

int main () {
   struct test * mytest = malloc(sizeof(struct test));
   ...
   printf("Address of the pointer x: %zu", &my_test->x); 
}

Upvotes: 0

Views: 72

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50775

Following code is meaningless :

x_tmp = mytest->x;
printf("Address pointed by x: %zu", &x_tmp); 

It just prints the address of the x_tmp variable whatever is contained in mytest and in mytest->x`.

Upvotes: 1

antonijn
antonijn

Reputation: 5760

You might be a bit confused. An int * is already an address, so in that case you could just use my_test->x (note that your application would segfault right away, since struct test *my_test doesn't point to anything).

If you want the address of the pointer (that would be an int **), you'd simply do &my_test->x.

Also it seems odd that you're assigning the int * to 5; that's a bit of a strange memory address. Perhaps you want to set the int at the location x to 5? In that case you'd write *my_text->x = 5.

Note that it's dangerous dereferencing pointers that don't point to anything sensible. You haven't assigned any pointers in your code, so they might just (they probably will) point to crap.

Upvotes: 2

Related Questions