我的程序有这些结构:
typedef struct Entry { // node
void *data; // whatever our data is, goes here
struct Entry *next; // next node
} Entry;
typedef struct {
int (*compare)(const void*a, const void *b); // compare func
Entry *top; // head
Entry *bottom; // tail
} *Queue;
并使用它们创建一个队列:
Queue create( int (*cmp)(const void*a, const void*b) ) {
Queue Q = NULL;
Q = (Queue)malloc(sizeof(Queue));
Q->top = NULL;
Q->bottom = NULL;
Q->top = malloc(sizeof(Entry));
Q->bottom = malloc(sizeof(Entry));
Q->compare = cmp;
return Q;
}
使用此插入:
void insert( Queue queue, void *data ) {
// start at the top
Entry *slot = queue->top;
Entry *newNode = malloc(sizeof(Entry));
newNode->data = data;
newNode->next = NULL;
// is it an entirely empty queue?
if (que_empty(queue)) {
// put our data into the dummy slot
queue->top = newNode;
}
}
从给定的主测试文件运行,该文件是正确的,无法修改(要插入的数据在全局变量中):
int main( void ) {
Queue up, down, fifo;
up = create( cmp_int64_ascend );
if( up == NULL ) {
fputs( "Cannot create ascending queue\n", stderr );
exit( EXIT_FAILURE );
}
down = create( cmp_int64_descend );
if( down == NULL ) {
fputs( "Cannot create descending queue\n", stderr );
exit( EXIT_FAILURE );
}
fifo = create( NULL );
if( fifo == NULL ) {
fputs( "Cannot create FIFO queue\n", stderr );
exit( EXIT_FAILURE );
}
puts( "Testing the ascending queue" );
process( up );
puts( "\nTesting the descending queue" );
process( down );
puts( "\nTesting the FIFO queue" );
process( fifo );
destroy( up );
destroy( down );
destroy( fifo );
return( 0 );
}
当我尝试运行它时,它开始无休止地重复看起来像指针地址(例如,18087952)和崩溃。我遇到的问题是queue-> top = newNode。
如何将newNode分配到队列的顶部?
答案 0 :(得分:3)
Queue Q = NULL;
Q = (Queue)malloc(sizeof(Queue));
Queue
这里是一个指针类型,所以你要分配指针的大小而不是结构的大小。
您可能不应该为指针类型指定类似Queue
的名称,这并不表示是指针 - 这只是令人困惑并导致上述错误。
最好为结构本身Queue
命名,并在需要指针的位置使用Queue*
。
答案 1 :(得分:1)
以下行不正确。
Q = (Queue)malloc(sizeof(Queue));
您没有分配足够的内存。你需要使用
Q = (Queue)malloc(sizeof(*Q));
使用malloc
时,这是一种很好的编程风格。您在计算尺寸时不太可能出错。
var = malloc(sizeof(*var));
关于插入错误......您有
void insert( Queue queue, void *data ) {
// start at the top
Entry *slot = queue->top;
Entry *newNode = malloc(sizeof(Entry));
newNode->data = data;
newNode->next = NULL;
// is it an entirely empty queue?
if (que_empty(queue)) {
// put our data into the dummy slot
queue->top = newNode;
}
// Where's the code to deal with the case when the queue is not empty????
}
这应该有效:
void insert( Queue queue, void *data ) {
Entry *newNode = malloc(sizeof(Entry));
newNode->data = data;
newNode->next = queue->top;
queue->top = newNode;
}