c - 从数组创建链表时 C 中的段错误

标签 c function linked-list segmentation-fault

正如我在标题中所说,我试图从一个数组生成一个链表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 结构的指针,现在在 ma​​in 函数中你试图使用 *first 指针,但需要分配内存空间才能使用。如果使用以下代码在使用前分配内存,则不会发生段错误。

first = (P*)malloc(sizeof(P));

关于c - 从数组创建链表时 C 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520389/

相关文章:

c - 有没有人使用结构来存储字符串和长度来实现 string.h 的替换?

function - 如何从函数列表和值构造函数?

python - 两个函数的 yield 可以相减吗?

c - 执行时间测量的通用功能

c - C 字节读取器中的段错误(核心转储)

c - 某处是否有任何 C 语言(甚至 C++)OpenID 库?

C - 读取字符数组中的 CSV 文件

c - Makefile fatal error : can't create obj/calc. o

python - 为什么在此实现中递归比迭代更快? (Python 反转链表)

c - 按字母顺序排列字符串的链接列表