通过内存分配错误连接字符串

时间:2016-01-05 09:04:29

标签: c dynamic-memory-allocation

我正在尝试使用内存分配将数组内的字符串相互连接起来。但我得到了错误,任何想法是什么导致它?谢谢。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {

const char *str[8] = { "one", "two", "three", "four",
    "five", "six", "seven", "eight" };
char *concat;
int total_size = 0;
int i = 0;

for (i = 0; i < 8; i++)
    total_size += strlen(str[i]) - 1;  // I put -1 for '\0' of each word.

concat = (char*)malloc(sizeof(char) * (total_size + 1));  // +1 for '\0'

concat = '\0';
for (i = 0; i < 8; i++) {
    strcat(concat, str[i]);

}

printf("%s\n", concat);
free(concat);
system("pause");
return 0;

}

1 个答案:

答案 0 :(得分:3)

你的假设在这里是错误的

total_size += strlen(str[i]) - 1;  // I put -1 for '\0' of each word.

删除- 1

另外

concat = '\0';

应该是

concat[0] = '\0';