每当我在 dev-C++ 中使用其中一个函数时(我知道它很旧,但出于某种原因仍在我的大学教授。)
strcat,strcpy,strcmp,strchr...//And their variants stricmp...
这些函数的第一个参数总是必须是一个数组(即:
char ch[]="hello";
但由于某种原因,它不能是指向字符串 bc 的指针,这会导致崩溃。 事实上,举个例子看看这两个代码:
代码1:
#include<stdio.h>
#include<string.h>
main()
{char ch[20]="Hello world!";
char *ch2="Hello Galaxy!";
strcat(ch,ch2);
printf("%s",ch);
scanf("%d")//Just to see the output.
}
这段代码工作正常并给出了预期的结果(Hello World!Hello Galaxy!)
但是反code2崩溃了。
代码2:
#include<stdio.h>
#include<string.h>
main()
{char ch[20]="Hello world!";
char *ch2="Hello Galaxy!";
strcat(ch2,ch);
printf("%s",ch2);
scanf("%d")//Just to see the output.
}
此代码崩溃并导致
file.exe has stopped working Error.
这对于几乎所有接受两个参数的字符串函数都是一样的。 这个问题是什么原因造成的。
最佳答案
使用 char *ch2 = "Hello Galaxy!";
,您将获得一个指向字符串文字的指针。您永远不应尝试修改字符串文字,因为这会调用未定义的行为(在您的情况下表现为崩溃)。
使用 char ch[20] = "Hello World!";
,您将使用字符串文字的内容初始化一个数组,因此您最终会在 ch
。
另外,请注意 20 个字符不足以容纳 Hello World!Hello Galaxy!
,这也是未定义的行为,称为缓冲区溢出。
关于带有数组和指针的 C 字符串函数(strcpy、strcat...、strstr),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11679050/