请看下面的代码,它做了一个简单的字符赋值
__global__ void seehowpointerwork(char* gpuHello, char* finalPoint){
char* temp;
bool found = false;
for(int i = 0 ; i < 11; i++){
if(gpuHello[i] == ' '){
temp = &gpuHello[i+1];
found = true;
break;
}
}
bool sth = found;
finalPoint = temp;
}
int main()
{
// Testing one concept;
string hello = "Hello World";
char* gpuHello;
cudaMalloc((void**)&gpuHello, 11 * sizeof(char));
cudaMemcpy(gpuHello, hello.c_str(), 11 * sizeof(char), cudaMemcpyHostToDevice);
char* didItFind;
char* whatIsIt = (char*)malloc(5 * sizeof(char));
seehowpointerwork<<<1,1>>>(gpuHello, didItFind);
cudaMemcpy(whatIsIt,didItFind, 5 * sizeof(char), cudaMemcpyDeviceToHost);
cout<<"The pointer points to : " << whatIsIt;
return 0;
}
我真的不明白,当我打印时whatIsIt
,为什么它不打印“世界”作为答案,而只是打印一些随机字符串。
如所指出的,在计算空字符后编辑更新版本
__global__ void seehowpointerwork(char* gpuHello, char* finalPoint){
char* temp;
bool found = false;
for(int i = 0 ; i < 11; i++){
if(gpuHello[i] == ' '){
temp = gpuHello;
found = true;
break;
}
}
bool sth = found;
finalPoint = temp;
}
int main()
{
// Testing one concept;
string hello = "Hello World";
char* gpuHello;
cudaMalloc((void**)&gpuHello, 12 * sizeof(char));
cudaMemcpy(gpuHello, hello.c_str(), 12 * sizeof(char), cudaMemcpyHostToDevice);
char* didItFind;
char* whatIsIt = (char*)malloc(6 * sizeof(char));
seehowpointerwork<<<1,1>>>(gpuHello, didItFind);
cudaMemcpy(whatIsIt,didItFind, 6 * sizeof(char), cudaMemcpyDeviceToHost);
cout<<"The pointer points to : " << whatIsIt;
return 0;
}