[问题]c语言的小问题

软件和网站开发以及相关技术探讨
回复
lin351139
帖子: 29
注册时间: 2008-06-10 17:20

[问题]c语言的小问题

#1

帖子 lin351139 » 2008-06-22 22:01

请高手看一下,为什么会不行,程序如下:
#include "stdio.h"
#include "malloc.h"
#define SIZE 10;
typedef struct node{
char data[10];
struct node *next;
}linknode;
typedef struct queueNode{
struct node *front,*rear;
}linkqueue;

linkqueue *q;

void creat(){
q->front=(linknode *)malloc(sizeof(linknode)); //这句显示出错
};
main(){
creat();
}
我是用netbeans写的c语言程序,编译器是gcc。
程序出输出的结果是 : Segmentation fault
为什么会这样啊。。我在xp里面用turbo c就可以运行。。
是不是ubuntu下的c语言跟xp下的有差别啊。。[/img]
linser
帖子: 243
注册时间: 2005-09-28 9:03

#2

帖子 linser » 2008-06-22 22:27

q指针还没有被正确初始化,当然会出错,应该先为q指针分配内存空间

代码: 全选

q = (linkqueue *)malloc(sizeof(linkqueue));
q->front=(linknode *)malloc(sizeof(linknode));
如果你不需要动态分配,那么可以把q声明为一个变量而不是指针

代码: 全选

linkqueue q;
q.front=(linknode *)malloc(sizeof(linknode));
跟上次某人犯了同一个错误 8)
lin351139
帖子: 29
注册时间: 2008-06-10 17:20

#3

帖子 lin351139 » 2008-06-22 22:39

不愧是高手。。。谢了。。
头像
command
帖子: 306
注册时间: 2007-10-14 0:50
来自: GUCAS

#4

帖子 command » 2008-06-22 22:39

代码: 全选

linkqueue *q; 
没有初始化。

代码: 全选

#include "stdio.h"
#include "malloc.h"
#define SIZE 10;
typedef struct node{
char data[10];
struct node *next;
}linknode;
typedef struct queueNode{
struct node *front,*rear;
}linkqueue;

linkqueue *q;

void creat(){
q = (linkqueue*)malloc(sizeof(linkqueue));
q->front=(linknode *)malloc(sizeof(linknode)); //这句显示出错
};
main(){
creat();
} 
OS: Debian GNU/Linux
Version: lenny
Kernel: 2.6.36
Xorg: 1.4.2
CPU: Intel(R) Core(TM)2 Duo CPU E8400 @ 3.00GHz
HD: 320G SATA
Memory: 2G DDRIII
Graphics:Mobility Radeon HD 3450
lintix
帖子: 21
注册时间: 2007-10-17 10:18

#5

帖子 lintix » 2008-07-06 11:53

可以先别把q声明成指针.这样貌似好理解点!

代码: 全选

#include "stdio.h" 
#include "malloc.h" 
#define SIZE 10; 
typedef struct node{ 
char data[10]; 
struct node *next; 
}linknode; 
typedef struct queueNode{ 
struct node *front,*rear; 
}linkqueue; 

linkqueue q; 

void creat(linkqueue *q){ 
q->front=(linknode *)malloc(sizeof(linknode));  
}; 
main(){ 

	creat(&q); 
}
flyinflash
帖子: 2376
注册时间: 2006-09-21 14:28

#6

帖子 flyinflash » 2008-07-06 21:22

一看就知道不看C之父的书的,一看就知道是喝M$尿的,一看就知道你老师也是是喝M$尿的。

http://wiki.ubuntu.org.cn/index.php?tit ... iant=zh-cn
回复