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

时间:2019-05-11 15:54:54

标签: malloc mpi

在我用C语言编写的MPI代码中,我从每个从属进程收到一个字。我想将所有这些单词添加到主端的char数组中(以下代码的一部分)。我可以打印这些单词,但不能将它们收集到单个char数组中。 (我认为最大字长为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: %s\n", 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�

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

让我们逐行细分

// 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);

由于您未初始化元素并且未将null终止,因此您正在调用未定义的行为。很高兴您没有让恶魔从鼻子里爬出来。

尽管如此,在C语言中,您可以仅通过赋值复制字符串。您的用例要求使用strncpy

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