正如我在标题中所说,我试图从一个数组生成一个链表。 P 是一个结构,包含float x 和指向列表中下一个元素的指针。 gen_list 函数一被调用,第一行代码“first->x = V[0]”就返回一个段错误,这是我从调试器中得到的结果:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004007f6 in gen_list (V=0x602010, n=10000, first=0x601068 <first>)
at main.c:46
46 (*first)->x = V[0];
(gdb)
我好像找不到问题,请帮忙!!
这里是重现错误所需的最少代码量:
typedef struct Popis {
float x;
struct Popis *next;}P;
P *first;
int main(){
float v[10];
v[0] = 1;
first->x = v[0];
}
我的代码:
P* gen_list(float V[], int n, P *first) {
first->x = V[0];
P *T = NULL;
P *new = NULL;
T = first;
t1 = clock();
for (int i = 1; i < n; i++) {
new->x = V[i];
T->next = new;
T = new;
}
T->next = NULL;
t2 = clock();
printf("\nTime for creation of linked list is: %dms", t2 - t1);
return first;}
最佳答案
段错误通常发生在错误的指针操作时,例如在您的示例代码中:
typedef struct Popis {
float x;
struct Popis *next;
} P;
P *first;
int main(){
float v[10];
v[0] = 1;
first->x = v[0];
}
看一下变量*first,它是一个指向 Popis 结构的指针,现在在 main 函数中你试图使用 *first 指针,但需要分配内存空间才能使用。如果使用以下代码在使用前分配内存,则不会发生段错误。
first = (P*)malloc(sizeof(P));
关于c - 从数组创建链表时 C 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520389/