Cuda char *变量分配 [英] Cuda char* variable assignment

查看:250
本文介绍了Cuda char *变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是本文中所选答案的跟进问题: cuda程序的输出与预期不符

This is a follow up question to the selected answer in this post: Output of cuda program is not what was expected.

以下功能有效:

__global__ void setVal(char **word)
{

    char *myWord = word[(blockIdx.y * gridDim.x) + blockIdx.x];
    myWord[0] = 'H';
    myWord[1] = 'e';
    myWord[2] = 'l';
    myWord[3] = 'l';
    myWord[4] = 'o';
}

为什么这行不通?

__global__ void setVal(char **word)
{

    char *myWord = word[(blockIdx.y * gridDim.x) + blockIdx.x];
    myWord = "Hello\0";

}


推荐答案

开始更加关注编译器的输出。您的第二个内核代码:

You should start paying much more attention to the output from the compiler. Your second kernel code:

__global__ void setVal(char **word)
{
    char *myWord = word[(blockIdx.y * gridDim.x) + blockIdx.x];
    myWord = "Hello\0";
}

编译为空内核,里面没有任何内容:

compiles to a null kernel with nothing inside it:

$ nvcc -arch=sm_20 -c nullkernel.cu 
nullkernel.cu(3): warning: variable "myWord" was set but never used

nullkernel.cu(3): warning: variable "myWord" was set but never used

之所以这样,是因为您认为的是字符串复制分配实际上只是一个指针分配,在这种情况下,编译器非常聪明,可以知道myWord没有写入内存,因此它消除了所有代码,并警告您未使用myWord。

The reason why is because what you think is a string copy assignment is really just a pointer assignment, and in this case the compiler is smart enough to know that myWord isn't written to memory, so it just eliminates all the code and warns you that myWord isn't used.

如果我要提出一个反问,并用这种方式重新编写代码:

If I were to ask a rhetorical question and re-write the code this way:

__global__ void setVal(char **word)
{

    char *myWord = word[(blockIdx.y * gridDim.x) + blockIdx.x];
    const char[] mymsg = "Hello\0";
    myWord = mymsg;
}

无论为什么代码不编译以及为什么可以编译,这一点都会更加明显从来没有隐式执行字符串副本分配,即使它确实编译了?

would be more obvious both why the code doesn't compile and why it could never "implicitly" perform a string copy assignment even if it did compile?

这篇关于Cuda char *变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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