简体   繁体   English

在C结构中访问指针的地址

[英]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? 如何访问指针x的地址?

SOLVED 解决了

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

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). 一个int *已经是一个地址,因此在这种情况下,您可以只使用my_test->x (请注意,由于struct test *my_test不指向任何内容,因此您的应用程序将立即struct test *my_test )。

If you want the address of the pointer (that would be an int ** ), you'd simply do &my_test->x . 如果您想要指针地址 (可以是int ** ),则只需执行&my_test->x

Also it seems odd that you're assigning the int * to 5 ; 您将int *分配给5似乎也很奇怪; that's a bit of a strange memory address. 那是一个奇怪的内存地址。 Perhaps you want to set the int at the location x to 5 ? 也许您想将x位置的int设置为5 In that case you'd write *my_text->x = 5 . 在这种情况下,您将编写*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. 您尚未在代码中分配任何指针,因此它们可能只是(可能会)指向废话。

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`. 它只是打印x_tmp变量的地址,无论mytest和mytest-> x`中包含什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM