看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) WINXP 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) code block 問題(Question): 我以為 test1 跟 test3 複製字串的原理應該相同 但是 執行到test3 程式會掛掉 兩者差異 只有test3是用struct包起來 不明白 為什麼test3不能執行 但是 test4 又可以正常執行 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> typedef struct { char *data; }element1; typedef struct { char data[10]; }element2; void main() { char *s1; char s2[10]; strcpy(s1,"test1"); printf("%s\n",s1); strcpy(s2,"test2"); printf("%s\n",s2); element1 item1; element2 item2; // strcpy(item1.data,"test3"); // printf("%s\n",item1.data); strcpy(item2.data,"test4"); printf("%s\n",item2.data); } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.220.35.157 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1534226819.A.13B.html
sarafciel: 指標沒有初始化前指到的位置未定義 08/14 14:13
不太確定您的意思 照您所說 s1 應該也沒初始值吧? 為什麼執行沒問題?
james732: 執行沒問題不代表程式沒問題 XD 08/14 14:23
您的意思是說 test1 跟 test3 都是錯誤的作法? 那應該怎麼做才正確 ※ 編輯: gcmtw88 (61.220.35.157), 08/14/2018 14:25:12
sarafciel: s1=(char *)malloc(10*sizeof(char)); 08/14 14:28
sarafciel: 對了 上面那篇忘了講 用完記得free(s1); 08/14 14:29
MOONRAKER: 開一個夠大的陣列就好了 再把s1指到那陣列 08/14 14:34
gcmtw88: 好的 明白為什麼錯了 謝謝 08/14 14:44