gcc3.0编译代码后,程序运行中出现的问题,不理解,请帮忙

FishCrazy 2003-08-10 11:00:08
最近编译以前写的一些代码包括实现链表、堆栈、二叉树和图的生成,插入,查询等功能,可是在编译通过之后运行程序会出现奇怪的现象,例如链表的代码大致如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
char data;
struct node *next;
}LNode;

int create(LNode *h){
LNode *ptr;
int i=0; int n=0;
char tmp;
h=NULL;
printf("input the number of list:\n");
scanf("%d",&n);
for(;i<n;i++){
printf("input the %dth node of list: ");
scanf(" %c",&tmp);
ptr=(LNode*)malloc(sizeof(LNode));
if(!ptr) return 0;
ptr->data=tmp;
ptr->next=h;
h=ptr;
}
return 1;
}

int main(int argc, char** argv){
LNode *head, *ptr;
if(!create(head)){
printf("failed.\n");
exit(0);
}
ptr=head;
printf("print list:\n"); /*断点 1*/
while(ptr!=NULL){
printf("%c",ptr->data);
ptr=ptr->next;
}
printf("it's end.\n");
return 1;
}



每当程序运行到“断点 1”的时候("print list:"会被打印),程序就会自动终止
请大家帮忙看看问题可能出在什么地方?

另外,堆栈、队列、二叉树的代码同样可以编译运行,但是运行之后程序不会在终端上打印出任何东西。
...全文
63 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ZhangYv 2003-08-11
  • 打赏
  • 举报
回复
*h只是传地址进去,并不是对head的引用,要特别小心得...
ZhangYv 2003-08-11
  • 打赏
  • 举报
回复
嘻嘻,一段时间不见功力退了很多嘛. :)
主要是head没有正确直到分配好空间.
LNode *create(LNode *h){
LNode *ptr;
int i=0; int n=0;
char tmp;
h=NULL;
printf("input the number of list:\n");
scanf("%d",&n);
for(;i<n;i++){
printf("input the %dth node of list: ");
scanf(" %c",&tmp);
ptr=(LNode*)malloc(sizeof(LNode));
if(!ptr) return 0;
ptr->data=tmp;
ptr->next=h;
h=ptr;
}
return h;
}
-------------------------------------
if(!(head = create(head))){
printf("failed.\n");
exit(0);
}
FishCrazy 2003-08-11
  • 打赏
  • 举报
回复
typedef struct{
int *top;
int *base;
int size;
}Stack;

这是一个用固定的空间作堆栈,用base指定的就是空间的首地址,
没听说过还有上面那中写法。

关于前面那段程序,为了方便后面出现的一个插入函数
int insert(LNode *h, int len); /*len为链表现有长度*/

int create(LNode *h){
... ...
return n; /*返回长度*/
}

调用时:
int len=0;
len=create(head);
....
insert(head,len);
ZhangYv 2003-08-11
  • 打赏
  • 举报
回复
不知道,也许是s的内存没有先被分配好.
s = (Stack*)malloc(sizeof(Stack));
s->base=(int*)malloc(INIT_SIZE*sizeof(int));
FishCrazy 2003-08-11
  • 打赏
  • 举报
回复
我记得自己尝试过这样的修改,不过会去试试的。
另外,写堆栈的时候,我发现运行时跳出的是:
#define INIT_SIZE 100
typedef struct{
... ...
}Stack;
----------------
Stack *s;

s->base=(int*)malloc(INIT_SIZE*sizeof(int)); <--跳出

怎么解释呢


最近真的退步了不少啊,去的那家公司做一些“业务核心”的工作
我发现自己反而是会计熟练了不少,觉得很悲凉...

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧