-2
#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;
}
欢迎来到C,你需要做你自己的内存分配。你不能将字符串复制到一个空数组char temp或者一个未初始化的指针char * temp中。你必须决定你想要多少空间,并且明确地分配那么多:'char temp [100]'或'char * temp = malloc(100)'。 –