访问C结构中指针的地址

时间:2014-02-20 11:17:42

标签: c pointers struct

我有一个结构:

struct test {
   int **x;
}

如何访问指针x的地址?

解决

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

2 个答案:

答案 0 :(得分:2)

你可能有点困惑。 int *已经是一个地址,因此在这种情况下您可以使用my_test->x(请注意,您的应用程序会立即发生段错误,因为struct test *my_test并未指向任何内容。)

如果您想要指针的地址(可能是int **),您只需执行&my_test->x

您将int *分配给5似乎很奇怪;这有点奇怪的内存地址。也许您想要将int设置为x5?在这种情况下,你要写*my_text->x = 5

请注意,引用指向危险的指针是危险的。你没有在你的代码中分配任何指针,所以他们可能只是(他们可能会)指向废话。

答案 1 :(得分:1)

以下代码毫无意义:

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

它只打印x_tmp变量的地址mytest和mytest-> x`中包含的内容。

相关问题