为什么 malloced 字符串不能与 strcat 一起使用?
Why doesn't malloced string not work with strcat?
在下面的代码中,在注释 strcat 时,str1 返回为最初声明的词“Enjoy”,但在使用 strcat 时,它会抛出段错误。我很困惑为什么自从我声明了一个动态分配的字符串后就没有进行连接。
char * kitchen(int cost)
{
cost = 100;
char *str1 = (char *)malloc(sizeof(char)* 70);
str1 = "\n Food's ready bruh, Enjoyy!!";
char *str2 = (char *)malloc(sizeof(char)* 70);
sprintf(str2, " But do pay %d", cost );
strcat(str1, str2);
return str1;
}
替换
str1 = "\n Food's ready bruh, Enjoyy!!";
有
strcpy(str1, "\n Food's ready bruh, Enjoyy!!");
尽管您进行了动态分配,"\n Food's ready bruh, Enjoyy!!"
仍然是字符串文字,并且仍被 C 视为只读。您的分配只是将 str1
指向该字符串文字。
在下面的代码中,在注释 strcat 时,str1 返回为最初声明的词“Enjoy”,但在使用 strcat 时,它会抛出段错误。我很困惑为什么自从我声明了一个动态分配的字符串后就没有进行连接。
char * kitchen(int cost)
{
cost = 100;
char *str1 = (char *)malloc(sizeof(char)* 70);
str1 = "\n Food's ready bruh, Enjoyy!!";
char *str2 = (char *)malloc(sizeof(char)* 70);
sprintf(str2, " But do pay %d", cost );
strcat(str1, str2);
return str1;
}
替换
str1 = "\n Food's ready bruh, Enjoyy!!";
有
strcpy(str1, "\n Food's ready bruh, Enjoyy!!");
尽管您进行了动态分配,"\n Food's ready bruh, Enjoyy!!"
仍然是字符串文字,并且仍被 C 视为只读。您的分配只是将 str1
指向该字符串文字。