Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                                                                                            
                
        
我有两个指针和一个int变量的结构。由于某种原因,我在ptr->i=0;行出现了分段错误。这是为什么?我指的是内存中的某些内容,i不是指针,因此应该合法。谁能解释这是怎么回事?我确实为结构和两个char指针创建了内存。

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,内存管理的知识,并花一些时间与您选择的调试器进行交流。

10-07 19:03
查看更多