如何将指针char数据(使用malloc创建)添加到C中的char数组



在我的MPI代码中,我从每个从工艺中收到一个单词。我想将所有这些单词添加到主侧的字符数组(下面代码的一部分(。我可以打印这些单词,但不能将它们收集到一个字符阵列中。(我认为最大单词长度为10,而奴隶的数量为slavenumber(

char* word = (char*)malloc(sizeof(char)*10);
char words[slavenumber*10];
for (int p = 0; p<slavenumber; p++){
    MPI_Recv(word, 10, MPI_CHAR, p, 0,MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Word: %sn", word); //it works fine
    words[p*10] = *word; //This does not work, i think there is a problem here.
}
printf(words); //This does not work correctly, it gives something like: ��>;&�>W�

有人可以帮助我吗?

让我们按行将其分解

// allocate a buffer large enough to hold 10 elements of type `char`
char* word = (char*)malloc(sizeof(char)*10);
// define a variable-length-array large enough to
// hold 10*slavenumber elements of `char`
char words[slavenumber*10];
for (int p = 0; p<slavenumber; p++){
    // dereference `word` which is exactly the same as writing
    // `word[0]` assigning it to `words[p*10]`
    words[p*10] = *word;
    // words[p*10+1] to words[p*10+9] are unchanged,
    // i.e. uninitialized
}
// printing from an array. For this to work properly all
// accessed elements must be initialized and the buffer
// terminated by a null byte. You have neither
printf(words);

由于您将元素不可分化而没有终止,因此您正在调用未定义的行为。很高兴您没有让恶魔从鼻子上爬出来。

严重,在C中,您可以单纯地通过分配来复制字符串。您的用法案例要求strncpy

for (int p = 0; p<slavenumber; p++){
    strncpy(&words[p*10], word, 10);
}

最新更新