[英]Segmentation fault when trying to concatenate an element of a 2d array
我想使用strcat()
連接字符串數組的元素。 我試過了:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char **str = malloc(sizeof(char *) * 3);
for (int i = 0; i < 3; i++) {
str[i] = malloc(sizeof(char) * 8);
}
str[0] = "foo";
str[1] = "bar";
strcat(str[0], "H");
for (int i = 0; i < 3; i++) {
printf("%s\n", str[i]);
}
free(str);
return 0;
}
我得到了錯誤:
Segmentation fault (core dumped)
我應該怎么做才能讓它正確?
對於初學者,該程序有 memory 泄漏。 起初 memory 被分配,其地址存儲在指針 str[i] 中
for (int i = 0; i < 3; i++) {
str[i] = malloc(sizeof(char) * 8);
}
然后指針 str[0] 和 str[1] 被字符串文字的地址重新分配。
str[0] = "foo";
str[1] = "bar";
因此,您可能無法通過此語句更改字符串文字
strcat(str[0], "H");
因為這會調用未定義的行為
你必須寫
strcpy( str[0], "foo" );
strcpy( str[1], "bar" );
而這個循環
for (int i = 0; i < 3; i++) {
printf("%s\n", str[i]);
}
還調用未定義的行為,因為元素 str[2] 未由字符串初始化。
您需要更改條件或循環(如i < 2
)或初始化元素 str[2]。
你需要釋放所有分配的 memory 像
for (int i = 0; i < 3; i++) {
free( str[i] );
}
free( str );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.