-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)'。 –