[問題] struct結構 字串複製問題
開發平台(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
→
08/14 14:13,
5年前
, 1F
08/14 14:13, 1F
不太確定您的意思
照您所說 s1 應該也沒初始值吧?
為什麼執行沒問題?
→
08/14 14:23,
5年前
, 2F
08/14 14:23, 2F
您的意思是說 test1 跟 test3 都是錯誤的作法?
那應該怎麼做才正確
※ 編輯: gcmtw88 (61.220.35.157), 08/14/2018 14:25:12
→
08/14 14:28,
5年前
, 3F
08/14 14:28, 3F
→
08/14 14:29,
5年前
, 4F
08/14 14:29, 4F
→
08/14 14:34,
5年前
, 5F
08/14 14:34, 5F
→
08/14 14:44,
5年前
, 6F
08/14 14:44, 6F