c程序中的strcat不起作用

4 c strcat strcat-s string.h

#include<string.h>
#include<stdio.h>
void main()
{
    char *str1="hello";
    char *str2="world";
    strcat(str2,str1);
    printf("%s",str2);
}
Run Code Online (Sandbox Code Playgroud)

如果我运行这个程序,我得到运行时程序终止.

请帮我.

如果我用这个:

char str1[]="hello";
char str2[]="world";
Run Code Online (Sandbox Code Playgroud)

然后它正在工作!

但为什么

char *str1="hello";
char *str2="world";
Run Code Online (Sandbox Code Playgroud)

这段代码不起作用????

gna*_*729 5

你正在学习一本糟糕的书.主要功能应声明为

int main (void);
Run Code Online (Sandbox Code Playgroud)

将其声明为void会在应用程序完成时调用未定义的行为.嗯,它还没有完成,但最终它会.

得到一本关于C语言的书.你会发现的

char *srt1="hello";
Run Code Online (Sandbox Code Playgroud)

编译好像你写的那样

static const char secret_array [6] = { 'h', 'e', 'l', 'l', 'o', 0 };
char* srt1 = (char*) &secret_array [0];
Run Code Online (Sandbox Code Playgroud)

char srt1[]="hello";
Run Code Online (Sandbox Code Playgroud)

编译好像你写的那样

char srt1 [6] = { 'h', 'e', 'l', 'l', 'o', 0 };
Run Code Online (Sandbox Code Playgroud)

两个strcat调用都是严重的错误,因为strcat调用的目标没有足够的内存来包含结果.第一次调用也是一个bug,因为你试图修改常量内存.在第一种情况下,这个bug会导致崩溃,这对你来说是一件好事并且很幸运.在第二种情况下,不会立即检测到错误.哪个运气不好.你可以打赌,如果你在一个运送给客户的程序中使用这样的代码,如果你运气不好就会崩溃,导致不正确的结果会给你的客户带来很多钱,否则你会被起诉.