gpt4 book ai didi

c - 使用一个struct来发音多个变量,报错

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

这是我的代码:

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

typedef struct test
{
int *a;
char *s;
}TEST;

int main (void)
{
TEST A,B;
A.a[0] = 1;
A.a[1] = 2;
A.s = "abc";
B.a[0] = 1;
printf("%s\n", A.s);
printf("%d\n", A.a[0]);
printf("%d\n", A.a[1]);
return 0;
}

当我编译时,我收到“Segmentation fault”。

当我删除行 B.a[0] = 1; 时,效果很好。为什么?

最佳答案

您通过使用具有自动存储持续时间的未初始化变量的值调用了未定义的行为,这是不确定的。

在使用它们之前,您必须分配一些缓冲区并将其分配给 A.aB.a

试试这个:

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

typedef struct test
{
int *a;
char *s;
}TEST;

int main (void)
{
TEST A,B;

/* add these 2 lines to allocate some buffer */
A.a = malloc(sizeof(int) * 2);
B.a = malloc(sizeof(int) * 2);

A.a[0] = 1;
A.a[1] = 2;
A.s = "abc";
B.a[0] = 1;
printf("%s\n", A.s);
printf("%d\n", A.a[0]);
printf("%d\n", A.a[1]);

/* add these 2 lines to free what you allocated */
free(A.a);
free(B.a);

return 0;
}

malloc() 添加错误处理将使这段代码更好。

关于c - 使用一个struct来发音多个变量,报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36078397/

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