首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

linux下段异常 快想破脑袋啦

2012-04-24 
linux下段错误 快想破脑袋啦#include stdio.h#include malloc.h#include stdlib.h#define SIZE 20ty

linux下段错误 快想破脑袋啦
#include <stdio.h>

#include <malloc.h>

#include <stdlib.h>

#define SIZE 20

typedef struct byte

{

  int size;

  int *base;

  int *top;

}stack;

void

creatStack(stack *p)

{

  p->base=malloc(SIZE*sizeof(int));

  p->top=p->base;

  p->size=SIZE;

}

void

conversion(int n,int d)

{

  int i;

  stack *p;

  creatStack(p);

 while(n)

  {

  push(p,n%d);

  n=n/d ;

  } 

while(!isEmpty(p))

  {

  i=pop(p);

  printf("%3d",i);

  }

}

int 

push(stack *p,int b)

{

  if(isFull(p))

  {

  printf("the stack if full");

  exit(1);

  }

 *(p->top++)=b;

}

int

isFull(stack *p)

{

  return p->top-p->base==SIZE;

}

int

pop(stack *p)

{

  if(isEmpty(p))

  {

  printf("the stack is empty");

  exit(1);

  }

  return *(--(p->top));

}

int 

isEmpty(stack *p)

{

  return p->base==p->top;

}

void 

main()

{

  int d;

  int n;

  printf("please input the n:");

  scanf("%d",&n);

  printf("please input d:");

  scanf("%d",&d);

  conversion(n,d);

  getch();

}

gdb显示错误是在creatStack中 求答案啊

[解决办法]

C/C++ code
voidcreatStack(stack *p)  //p不知道指哪里{  p->base=malloc(SIZE*sizeof(int));  //p都不知道指哪里,malloc分配的空间地址存放在哪里?  p->top=p->base;  p->size=SIZE;}voidconversion(int n,int d){  int i;  stack *p;   //这里p是个指针,没有分配空间存储stack里面的变量  creatStack(p); //p指向哪里? while(n)  {  push(p,n%d);  n=n/d ;  }  while(!isEmpty(p))  {  i=pop(p);  printf("%3d",i);  }}
[解决办法]
楼上正解,可以在main函数里先 stack st;再stack *p=st;conversion函数加一个指针参数,把p传进去

热点排行