【发布时间】:2017-10-22 23:55:48
【问题描述】:
我有一个函数可以将一个结构插入到一个作为链表实现的队列中。 我正在传递一个数组元素作为进程。
void q_insert (queue *q, process p) {
printf("before insert attemp\n");
if (q->head == NULL) {
q->head = malloc(sizeof(struct Node));
q->head->process = &p;
q->head->next = NULL;
q->tail = q->head;
printf("After insertion into empty\n");
}
else {
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->process = &p;
temp->next = NULL;
q->tail->next = temp;
q->tail = temp;
printf("after insertion into non empty\n");
}
}
当我第一次在一个空列表上调用这个函数时,它似乎工作正常。当我尝试插入第二个项目时,它会添加第二个条目,但它也会用第二个条目的副本替换第一个条目。这些是使用的结构:
typedef struct {
char name[80];
int arrival_time;
int execution_time;
int priority; // high number is high priority
} process;
struct Node{
process* process;
struct Node* next;
} q_node;
typedef struct {
struct Node* head;
struct Node* tail;
} queue;
【问题讨论】:
-
q->head->process = &p;:p是q_insert函数中的局部值。修复示例 E.gprocess* process;-->process process;..q->head->process = p; -
@BLUEPIXY 太棒了。谢谢。大约一年没用过 C 指针了。忘记的比我想象的要多。你现在正在救我。
标签: c linked-list