简体   繁体   English

如何获取变量地址的地址(&&是编译器错误)?

[英]How do I get the address of the address of a variable (&& is a compiler-error)?

I have a quick question that I can't seem to find online. 我有一个快速的问题,似乎无法在网上找到。

I am using CUDA to do some GPU work, and I need some data allocated on the GPU. 我正在使用CUDA来完成一些GPU工作,并且我需要在GPU上分配一些数据。 The cudaMalloc function goes like this: cudaMalloc函数如下所示:

cudaMalloc(void** identifier, size_t space);

Easy enough. 很简单。 So, let's allocate an integer. 因此,让我们分配一个整数。

int i = 5;
cudaMalloc((void**)&(&i), sizeof(int));

But this errors ("expression must be an lvalue or a function designator"). 但是会出现这种错误(“表达式必须是左值或函数指示符”)。 The apparent workaround is to declare i as a pointer to begin with, and then take the address of it, and that works perfectly fine; 一种明显的解决方法是将i声明为开头,然后获取它的地址,这样就可以很好地工作。 I just hate workarounds. 我只是讨厌解决方法。

I feel like this question should have an obvious answer - after all, the ** , *** and even ********** work just fine in C. So, how do I get the address of the address of a variable 'cleanly'? 我觉得这个问题应该有一个明显的答案-毕竟*****甚至**********在C语言中都可以正常工作。因此,我如何获得该地址的地址变量“干净地”?

Thanks! 谢谢!

That's not a workaround; 不是解决方法; that's the right way to do it. 这是正确的方法。

The function wants the address of a pointer to int , because it's going to set that pointer to point to an int that it has just allocated. 该函数想要一个指向int的指针的地址,因为它将设置该指针指向它刚分配的int Therefore you need the address of a real, allocated pointer. 因此,您需要一个真实的,已分配指针的地址。 An expression like "&&i" asks the compiler to give you the address of i -- which is a pure number, with no storage location -- and then give you a pointer to that value, which of course it can't do. 诸如“ && i”之类的表达式要求编译器为您提供i的地址(这是一个纯数字,没有存储位置),然后为您提供指向该值的指针,这当然是不行的。

So you want to say 所以你想说

int *p;
cudaMalloc((void**)&p, sizeof(int));

Now *p is the int that was allocated. 现在*p是分配的int

Taking the address of an address isn't possible. 无法取得地址的地址。 Only objects have addresses, and an address is not an object. 只有对象才有地址,而地址不是对象。 You can assign an address to a pointer (which is an object) and then take the address of that pointer, which is what you describe as your 'workaround'. 您可以为一个指针(是一个对象)分配一个地址,然后获取该指针的地址,这就是您所说的“解决方法”。

You cannot get a reference to a reference because &i is not stored anywhere, you can't access its memory location since it doesn't exist. 您无法获得对引用的引用,因为&i不会存储在任何地方,因为它不存在,所以无法访问其内存位置。

You should use a pointer to an int. 您应该使用一个指向int的指针。

int *i = calloc(sizeof(int),1);

then its reference will be an address of a pointer variable which is stored somewhere. 那么它的引用将是存储在某处的指针变量的地址。 Of course you can't do it in a local scope if pointer needs to be valid also outside scope because you would allocate on the stack. 当然,如果指针在范围外也需要有效,则不能在本地范围内执行此操作,因为您将在堆栈上进行分配。

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

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