我是c的新编码,我使用指针不是很好。代码编译很好,但运行它会产生分段错误。我把它缩小到我创建节点的地方(我认为),但我不知道如何修复它。任何帮助都会很棒!感谢。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
/* STRUCTURES */
struct Node
{
int id;
int at;
struct Node* prev;
struct Node* next;
};
struct Queue
{
struct Node* head;
struct Node* tail;
};
/* GLOBAL VARIABLES */
struct Queue* orderedArrival; // holds original queue setup
struct Queue* waitQueue; // changeable copy of above
/* METHODS */
void addByArrivalTimes(struct Node* process, struct Queue* queue);
void printQueue(struct Queue* queue);
/* MAIN */
int main()
{
orderedArrival = malloc(sizeof orderedArrival);
if (orderedArrival == NULL)
return 0;
waitQueue = malloc(sizeof waitQueue);
if (waitQueue == NULL)
return 0;
orderedArrival->head = orderedArrival->tail = NULL;
waitQueue->head = waitQueue->tail = NULL;
int i;
for(i = 0; i < 10; i++) //10 processes
{
struct Node* process;
process = malloc(sizeof *process);
process->next = NULL;
process->prev = NULL;
process->id = i;
process->at = rand()%10;
addByArrivalTimes(process, orderedArrival);
}
printQueue(orderedArrival);
return 1;
}
// Method is to put processes in order by arrival time
void addByArrivalTimes(struct Node* process, struct Queue* queue)
{
// Queue is Empty
if(queue->head == NULL)
{
queue->head = process;
queue->tail = process;
}
// Queue is not Empty
else
{
struct Node* q = queue->tail;
struct Node* p = queue->head;
// Add at end
if(process->at > q->at)
{
queue->tail = process;
process->prev = q;
q->next = process;
}
// Add at beginning
else if(p->at > process->at)
{
queue->head = process;
process->next = p;
p->prev = process;
}
// Add in the middle
else
{
while(p->at < process->at)
p = p->next;
q = p->prev;
q->next = process;
p->prev = process;
process->prev = q;
process->next = p;
}
}
}
void printQueue(struct Queue* queue)
{
struct Node* p = queue->head;
while(p != NULL)
{
printf("Process: %d, Arrival Time: %d\n", p->id, p->at);
p = p->next;
}
}
答案 0 :(得分:1)
在malloc
中,您对变量使用sizeof
而非您需要更改的数据类型:
int main(int argc, char* argv[])
{
orderedArrival = malloc(sizeof(struct Queue));
if (orderedArrival == NULL)
return 1;
waitQueue = malloc(sizeof(struct Queue));
if (waitQueue == NULL)
return 1;
//...