#include <stdio.h>
#include <string.h>
int main(void){
char s[] = "dog";
char t[] = "house";
char temp[]="";
strncpy(temp, s, 2);
return 0;
}
那么temp就是“do”第一个字符的地址; 我通过 char temp[] 将此代码调整为 char *temp 但是这段代码是错误的,为什么呢?
#include <stdio.h>
#include <string.h>
int main(void){
char s[] = "dog";
char t[] = "house";
char *temp;
strncpy(temp, s, 2);
return 0;
}
最佳答案
两个代码都是错误的。
第一个仅在 temp
中为 1 个字符分配空间,但复制 2 个字符。
第二个获取字符串文字的地址并通过该地址写入字符串文字。字符串文字是只读的,因此这可能会崩溃。
所有这些都是编译器不一定诊断的错误(技术术语是“行为未定义”)。
关于c - 这段代码有什么不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36824044/