[問題] 練習stack結構 資料顯示問題

作者: gcmtw88 (前方黃昏)   2018-08-14 13:46:09
開發平台(Platform): (Ex: Win10, Linux, ...)
WIN XP
問題(Question):
分別
手動加入元素 item0~3
以及for迴圈
自動加入元素到stack
用for迴圈加入的元素
感覺怪異
不知道哪邊想錯了
預期的正確結果(Expected Output):
item=test0
item=test1
item=test2
item=test3
item=test4
item=test5
item=test6
item=test7
s1.length=7
test0
test1
test2
test3
test4
test5
test6
test7
錯誤結果(Wrong Output):
item=test0
item=test1
item=test2
item=test3
item=test4
item=test5
item=test6
item=test7
s1.length=7
test0
test1
test2
test3
test7
test7
test7
test7
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
完整程式
https://pastebin.com/sHABbnTi
部份程式
void Push(StackADT *S,element item)
{
if(isFull(S))
printf("stack is full \n");
else
{
printf("item=%s\n",item);
S->stack[++(S->length)]=item;
}
}
int main()
{
//初始化STACK
StackADT s1;
s1.length=-1;
//手動加入stack元素
element item0;
item0.data="test0";
Push(&s1,item0);
element item1;
item1.data="test1";
Push(&s1,item1);
element item2;
item2.data="test2";
Push(&s1,item2);
element item3;
item3.data="test3";
Push(&s1,item3);
//自動加入stack元素
int j;
for(j=4;j<8;j++)
{
element item;
char buf[10];
sprintf(buf,"test%d",j);
item.data=buf;
Push(&s1,item);
}
//顯示stack目前長度
printf("s1.length=%d\n",s1.length);
//顯示stack內容
int i;
for (i=s1.length;i>=0;i
作者: sarafciel (Cattuz)   2018-08-14 14:07:00
你的elem的data是指標 4~7都指到buff上buff內容有改當然4~7都會受到影響只會在stack上配一次而已 寫在哪都一樣 除非你用到heapchar *buf = (char *)malloc(10*sizeof(char));
作者: MOONRAKER (㊣牛鶴鰻毛人)   2018-08-14 14:35:00
就你記錯這樣
作者: gcmtw88 (前方黃昏)   2018-08-14 14:52:00
把下面那篇的問題解決 就知道怎麼傳遞字串了 謝謝各位

Links booklink

Contact Us: admin [ a t ] ucptt.com