我有一个带有两个指针和一个 int 变量的结构。由于某种原因,我在 ptr->i=0;
行遇到段错误。这是为什么?我指着内存中的某个东西,i
不是指针,所以它应该是合法的。谁能解释一下这是怎么回事吗?我确实为结构体和两个字符指针创建了内存。
struct A_ {
char *a;
char *b;
int i;
};
typdef struct A_ StructA;
然后在我的 main()
中我有以下内容:
StructA *ptr=malloc(sizeof(StructA));
ptr->a=malloc(sizeof(char));
ptr->b=malloc(sizeof(char));
ptr->i=0;
最佳答案
您没有指向内存中的任何内容,因为 ptr
尚未初始化。
编辑:您在代码中的其他地方做错了。以下compiles and runs to completion 。您应该根据以下内容对代码进行建模:
#include <stdio.h>
typedef struct A {
int i;
} A;
int main(void) {
A *a = malloc(sizeof(A));
a->i = 42;
printf("%d", a->i);
free(a);
return 0;
}
更重要的是,我建议花时间阅读 C 语言、内存管理,并花一些时间使用您选择的调试器。
关于c - 将变量设置为 0 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18859117/