为什么cudaMalloc()使用指针的指针? [英] Why does cudaMalloc() use pointer to pointer?

查看:842
本文介绍了为什么cudaMalloc()使用指针的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如, cudaMalloc((无效**)及device_array,NUM_BYTES);

这个问题一直问过和得到的答复是因为 cudaMalloc 返回一个错误,code,但我不明白这一点 - 什么东西有双指针得到了与返回错误code呢?为什么不能简单的指针做的工作?

This question has been asked before, and the reply was "because cudaMalloc returns an error code", but I don't get it - what has a double pointer got to do with returning an error code? Why can't a simple pointer do the job?

如果我写

cudaError_t catch_status;
catch_status = cudaMalloc((void**)&device_array, num_bytes);

错误code将放在 catch_status ,并返回一个简单的指向分配GPU内存就足够了,不应该吧?

the error code will be put in catch_status, and returning a simple pointer to the allocated GPU memory should suffice, shouldn't it?

推荐答案

在C,数据可以通过值或通过的模拟通按引用的(由指针即数据)。由值是单向的方法,由指针允许的功能和它的调用环境之间的双向数据流。

In C, data can be passed to functions by value or via simulated pass-by-reference (i.e. by a pointer to the data). By value is a one-way methodology, by pointer allows for two-way data flow between the function and its calling environment.

当一数据项被传递到通过函数的参数列表的功能,并且该功能被预期,使得修改后的值中的呼叫环境最多显示修改的原始数据项,这样做的正确的C的方法是通过通过指针的数据项。在C中,当我们通过由指针,我们取项的地址被修改,创建一个指针(可能的指针在这种情况下,指针)和手地址的功能。这允许在呼吁环境修改原来的项目(通过指针)的功能。

When a data item is passed to a function via the function parameter list, and the function is expected to modify the original data item so that the modified value shows up in the calling environment, the correct C method for this is to pass the data item by pointer. In C, when we pass by pointer, we take the address of the item to be modified, creating a pointer (perhaps a pointer to a pointer in this case) and hand the address to the function. This allows the function to modify the original item (via the pointer) in the calling environment.

通常的malloc 返回一个指针,我们可以使用赋值在调用环境来分配这个返回的值到所需的指针。在 cudaMalloc 的情况下,CUDA设计者选择使用的返回值进行错误状态,而不是一个指针。因此在调用环境指针的设置必须经由传递给函数的参数之一时,通过参考(即通过指针)。既然是的指针值的,我们要设置,就必须把指针(创建一个指针的指针)的地址,该地址传递给 cudaMalloc 功能。

Normally malloc returns a pointer, and we can use assignment in the calling environment to assign this returned value to the desired pointer. In the case of cudaMalloc, the CUDA designers chose to use the returned value to carry an error status rather than a pointer. Therefore the setting of the pointer in the calling environment must occur via one of the parameters passed to the function, by reference (i.e. by pointer). Since it is a pointer value that we want to set, we must take the address of the pointer (creating a pointer to a pointer) and pass that address to the cudaMalloc function.

这篇关于为什么cudaMalloc()使用指针的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆