【发布时间】:2017-05-19 17:09:57
【问题描述】:
我需要在 C 中编写队列结构以进行分配。节点有一个指向下一个节点的指针和值(到目前为止,很正常)。但是,由于我需要将它与线程一起使用,我将 malloc 堆上的所有容量。 但是,节点和队列是这样定义的:
//Element of a queue
struct queue_node {
// Pointer to next element in the queue
struct queue_node* next;
// Value/Data of the queue element
int value;
};
// Queue data structure
struct queue {
// Head of the linked list
struct queue_node* head;
// Max capacity of the queue
int capacity;
// Current size of the queue. size <= capacity, always
int size;
};
我遇到的问题是推送元素,因为我没有任何关于分配内存的开始或结束的信息。所以我决定让头节点始终是空间中的第一个节点,这样我就可以使用容量 我编写了这样的基本功能:
struct queue* queue_new(int capacity){
struct queue_node* head1 = malloc(sizeof(struct queue_node)*capacity);
struct queue* ret = malloc(sizeof(struct queue));
/*
struct queue_node head2;
head2.next = NULL;
(*head1) = head2;
*/
(*head1).next = NULL;
(*ret).head = head1;
(*ret).size = 0;
(*ret).capacity = capacity;
return ret;
}
void queue_delete(struct queue* queue){
free((*queue).head);
free(queue);
}
所以。但是,当我想将某些东西推入队列时,我会遇到麻烦。显然,要做的第一件事,就是填满脑袋。这似乎奏效了。但是将元素附加到头节点不会:
int queue_push_back(struct queue* queue, int value){
if((*queue).size >= (*queue).capacity){
return -1;
}else if((*queue).size == 0){
(*(*queue).head).value = value;
(*queue).size++;
return (*queue).size;
} else{
if((*(*queue).head).next == NULL){ ////((*queue).head + sizeof(struct queue_node))
printf("Intern queue size 1: %d\n", (*queue).size);
(*(*queue).head).next = ((*queue).head + sizeof(struct queue_node));
printf("Error here?\n");
(*(*(*queue).head).next).value = value;
printf("Error here 2?\n");
(*(*(*queue).head).next).next = NULL;
printf("Error here 3?\n");
printf("Intern queue size 2: %d\n", (*queue).size);
printf("Intern queue capacity: %d\n", (*queue).capacity);
(*queue).size++;
return (*queue).size;
}
}
我跳过了常见情况的代码,因为这甚至不起作用。出于某种原因,如果我想推送第二个元素,它会覆盖我的队列结构。我不知道为什么。 有人可以帮我告诉我,我哪里做错了吗?
【问题讨论】:
-
无论如何,请使用
->运算符...(*(*(*queue).head).next).next不清晰,应该是queue->head->next->next然后请编辑您的代码以创建Minimal, Complete, and Verifiable example。这绝对是错误的,因为它不分配内存:(*(*queue).head).next = ((*queue).head + sizeof(struct queue_node)); -
如果一个答案解决了你的问题,不要只是在标题中“解决”了,而是mark the answer as accepted。
标签: c pointers struct queue malloc