Char 转义序列-它是什么意思

char escape sequence - what does it mean?

本文关键字:意思 它是什么 转义序列 Char      更新时间:2023-10-16

我正在看这个例子

CUDA真正的"Hello World!"

中的
char str[16] = "Hello ";

代表什么?

我不知道为什么16字符str"Hello "里面,然后所有的零然后(这不是一个全局变量)。我怎么确定它只包含0 ?"

''是ASCII NUL 空字符 (ASCII码为0)。

指定数组中所有的零字节是没有意义的。以下是等价的:

char str[16] = "Hello ";
char str[16] = "Hello ";

如果数组进行了部分初始化,则未初始化的元素接收相应类型的值0。(IBM) <一口>

由于长度为16,编译器将自动确保数组的其余部分(在"Hello "为零之后)。作者这样做要么是为了"确保"数组的其余部分为零,要么是为了给读者提供文档。

与我们最初的分析相反,CUDA内核是而不是"戳入字节"以将World!附加到现有字符串上。首先打印Hello。然后内核将字符串修改为World!,最后输出。

字符串被指定为16字节的唯一原因是,这是内核设计用来工作的块大小,他们必须确保内核不干扰内存,这是不应该的。

我在(部分)原始代码中添加了一些注释,以使这一切更清楚:

__global__                              // The kernel which is run in parallel
void hello(char *a, int *b) 
{
    a[threadIdx.x] += b[threadIdx.x];
}
int main()
{
    // The line in question. There's really no point in padding it with zeros.
    // The zeros are *not* replaced, and only 12+1 bytes are being specified.
    char a[N] = "Hello ";
    // These values are added (by the CUDA kernel) to the array above. Again,
    // since partial arrays are zero-filled, there's no point in filling this in.
    int b[N] = {15, 10, 6,  0, -11,  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    // 'H' + 15 = 'W'
    // 'e' + 10 = 'o'
    // 'l' + 6  = 'r'
    // 'l' + 0  = 'l'
    // 'o' - 11 = 'd'
    // ' ' + 1  = '!'
    char *ad;
    int *bd;
    const int csize = N*sizeof(char);
    const int isize = N*sizeof(int);
    printf("%s", a);                  // Print "Hello "
    cudaMalloc( (void**)&ad, csize ); 
    cudaMalloc( (void**)&bd, isize ); 
    cudaMemcpy( ad, a, csize, cudaMemcpyHostToDevice ); 
    cudaMemcpy( bd, b, isize, cudaMemcpyHostToDevice ); 
    dim3 dimBlock( blocksize, 1 );
    dim3 dimGrid( 1, 1 );
    hello<<<dimGrid, dimBlock>>>(ad, bd);   // Add the values in b to a

    cudaMemcpy( a, ad, csize, cudaMemcpyDeviceToHost ); 
    cudaFree( ad );
    cudaFree( bd );
    printf("%sn", a);               // print "World!"
    return EXIT_SUCCESS;
}

代表NUL, Nul用作字符串终止字符。意思是它表示字符串的结尾。NUL字节的值为0x00

如前所述,它没有什么意义。只是将代码为0的字符放在那里,但无论如何都会发生。在数组边界没有给定的情况下(因为额外的0将被计算在内),或者在0之后有更多字符的情况下,可以很好地使用该方法。

char foo_and_bar[] = "FooBar";

将用0分隔部分