【发布时间】:2018-01-04 15:26:20
【问题描述】:
我是 C 语言的新手。我正在尝试使用 strcat 函数。
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[]) {
char s1[] = "12345";
char s2[] = "abcde";
strcat(s1, s2);
puts(s1);
puts(s2);
return 0;
}
这个运行正常,但是
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[]) {
char* s1 = "12345";
char* s2 = "abcde";
strcat(s1, s2);
puts(s1);
puts(s2);
return 0;
}
最后一个未能返回结果。为什么两种不同的声明方式在strcat函数中会返回不同的结果。提前致谢。
【问题讨论】:
-
bash -> man strcat
-
你似乎相信它分配了它需要的内存。好吧,它没有。
-
这两个都是未定义的行为。
-
当用作函数参数定义之外的变量定义的一部分时,
char s1[] = "..."和char * s1 = "..."会做完全不同的事情。 -
提示:“这个运行正常”更像是“这个运行正常”。使用 C,代码应该“打破规则”,有时,代码仍然“有效”。
标签: c string pointers c-strings strcat