gpt4 book ai didi

c - 为什么在以下 C 代码中出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:52 25 4
gpt4 key购买 nike

#include<stdio.h>
#include <stdlib.h>

struct a1 {
int value ;
};

struct cf {
struct a1 *a1;
int val;
};

main(){

struct cf *cf = malloc(sizeof(struct cf));

cf->a1->value = 45;
printf("cf->a1->value = %d \n",cf->a1->value);

}

当我试图执行此 C 代码时,我遇到了段错误(核心已转储)!

最佳答案

原因是您正在为 cf 而不是为 a1 分配所需的内存。你必须做类似的事情

#include<stdio.h>
#include <stdlib.h>

struct a1 {
int value ;
};

struct cf {
struct a1 *a1;
int val;
};

main(){

struct cf *cf = malloc(sizeof(struct cf));
cf->a1 = malloc(sizeof(struct a1));
cf->a1->value = 45;
printf("cf->a1->value = %d \n",cf->a1->value);

}

关于c - 为什么在以下 C 代码中出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22020230/

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