作者gcmtw88 (前方黄昏)
看板C_and_CPP
标题[问题] 练习stack结构 资料显示问题
时间Tue Aug 14 13:46:09 2018
开发平台(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--)
printf("%s\n",s1.stack[s1.length-i]);
return 0;
}
补充说明(Supplement):
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.220.35.157
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1534225572.A.2A1.html
※ 编辑: gcmtw88 (61.220.35.157), 08/14/2018 13:51:44
1F:→ sarafciel: 你的elem的data是指标 4~7都指到buff上 08/14 14:07
2F:→ sarafciel: buff内容有改当然4~7都会受到影响 08/14 14:08
在回圈中
每次执行 都宣告一次 char buf[10];
我以为 每次都会重新给 buf新的记忆体空间
实际上不是这样吗?
※ 编辑: gcmtw88 (61.220.35.157), 08/14/2018 14:12:35
3F:→ sarafciel: 只会在stack上配一次而已 写在哪都一样 除非你用到heap 08/14 14:20
4F:→ sarafciel: char *buf = (char *)malloc(10*sizeof(char)); 08/14 14:20
所以说 我for中的element item;
每次回圈 item都是取用同一块记忆体?
怎嚜记得 宣告一次 就会取新的一块记忆体
※ 编辑: gcmtw88 (61.220.35.157), 08/14/2018 14:29:38
5F:→ MOONRAKER: 就你记错这样 08/14 14:35
好的 谢谢指教
那请问 想要把元素 for回圈 推入stack
我应该用什麽方法
目前暂时没想到怎麽传递不同字串
※ 编辑: gcmtw88 (61.220.35.157), 08/14/2018 14:38:29
6F:→ gcmtw88: 把下面那篇的问题解决 就知道怎麽传递字串了 谢谢各位 08/14 14:52