我打算编写一个简单的 SDL 应用程序,所以我想我应该实现一个可以稍后扩展的简单链表。现在经过一番挣扎后,我决定在这里寻求帮助。
我知道链表,我读过它。我看到了几个实现,不是那么难,很容易掌握。所以我想我应该能够自己实现一个。我猜我在这里严重忽略了一些东西。:(
首先这段代码编译不好,分段错误。其次,不幸的是,如果我能克服我用指针做的基本错误,我认为它不会产生我想要的东西。
你能告诉我我的代码中的错误吗?我在哪里做错了?
这是一个用于编辑的 liveworkspace 链接 http://liveworkspace.org/code/1qu1RN $1
这是我在 Cygwin gcc 上遇到的错误
temp [v 0] -> 0.460241 0.000000 0.050356
temp [v 1] -> 0.072079 0.153807 0.864573
temp [v 2] -> 0.683917 0.709301 0.080479
temp [v 3] -> 0.295755 0.264795 0.894696
address of ptemp @ 1629101750
[v 0] -> linked vertex is 7731159828445146316135105405324534341657178000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000 578395405356271.125000 1310047834864691498231654014730274851713450000.000000
Segmentation fault (core dumped)
这是代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NEWline printf("\n")
typedef struct position {
double x;
double y;
double z;
} position;
struct datalist {
position v;
struct datalist *pnext;
};
typedef struct datalist datalist;
void initializeList (datalist *head);
void addList_II (datalist *head , double data[3] );
void initializeList (datalist *head){
position pv= {0,0,0};
head = (datalist *) malloc ( sizeof (head) );
if (head == NULL){ printf("cannot allocate memory"); exit(1); }
head->v=pv;
head->pnext=NULL;
}
void addList_II ( datalist *head , double data[3] ) {
datalist *adddata;
adddata = (datalist *)malloc ( sizeof (datalist) );
if (adddata == NULL) { printf("cannot allocate memory for insertion data"); exit(1); }
adddata->v.x = data[0];
adddata->v.y = data[1];
adddata->v.z = data[2];
adddata->pnext = head->pnext;
head=adddata;
}
int main() {
datalist *ptemp;
datalist temp;
int i,c; //counters
datalist *head;
initializeList(head);
for ( i = 0; i < 4; i++ ) {
double t[3];
srand ( time ( NULL )*i+234 );
temp.v.x = ((double ) rand() )/ RAND_MAX;
srand ( time ( NULL )*i*546 );
temp.v.y = ((double ) rand() )/ RAND_MAX;
srand ( time ( NULL )*i*567+345 );
temp.v.z = ((double ) rand() )/ RAND_MAX;
t[0] = temp.v.x; t[1] = temp.v.y; t[2] = temp.v.z;
printf ( "temp [v %d] -> %F %F %F \n",i, temp.v.x, temp.v.y, temp.v.z );
addList_II (head, t );
}
c=0;
ptemp=head;
while (ptemp!=NULL) {
printf("[v %d] -> linked vertex is %F %F %F \n", c, ptemp->v.x,ptemp->v.y, ptemp->v.z);
ptemp=ptemp->pnext;
}
}