gpt4 book ai didi

c - 结构指针 i c 中的段错误

转载 作者:行者123 更新时间:2023-11-30 18:55:48 25 4
gpt4 key购买 nike

下面是我的 C 程序给我段错误,我不知道为什么。进一步的 sizeof (struct node1*) 给出答案 4 ,而 sizeof (struct node1) 给出答案 12 。请解释一下。

#include<stdio.h>
#include<malloc.h>

struct node{
int i;
int j;
};

struct node1{
int *a;
int *b;
struct node *n;
};

int main()
{
struct node1 *nn;
nn=(struct node1 *)malloc(sizeof(struct node1));
nn->n->i=5;
printf("\nsize is %d -- %p -- %p %d\n",sizeof (struct node1*),*nn,nn,nn->n->i);

return 0;
}

最佳答案

出现段错误,因为“node1”结构的“n”成员未分配。第一次分配后,在 nn->n 上使用 malloc。

struct node1 *nn;

nn=(struct node1 *)malloc(sizeof(struct node1));
nn->n = malloc(sizeof(struct node));
//now nn->n is allocated you can set a value in nn->n->i
nn->n->i=5;

不要忘记“return 0”之前的 Free call

free(nn->n);
free(nn);
return 0;

关于c - 结构指针 i c 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26385084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com