访问字段导致取消引用 C 中的空指针

Access to field results in dereference of a null pointer in C

这个问题是关于C编程语言的: 我收到错误消息:访问字段 'x' 导致取消引用空指针

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

typedef struct A {  
    int *x;  
    int *y;  
} A;  

void allocateStruct(int sizeN, A *aType);
void printInfo(A *aType);
  
int main() {   
    A *genericA;  
    allocateStruct(5, genericA);  
    int x[5] = {2, 3, 4, 5, 6};  
    int y[5] = {12, 36, 40, 52, 23};   

    genericA->x = x;  
    genericA->y = y;  
    printInfo(genericA);   
}  

void allocateStruct(int sizeN, A* aType) {  
    aType->x = (int*)malloc(sizeN * sizeof(int));   
    aType->y = (int*)malloc(sizeN * sizeof(int));    
}  
 
void printInfo(A *aType) { 
    printf("%i %i\n",  aType->x[0], aType->y[0] ); 
} 

您尚未为该结构分配内存,但您正在访问它的成员

void allocateStruct(int sizeN, A* aType) {
    aType->x = (int*)malloc(sizeN * sizeof(int));   
    aType->y = (int*)malloc(sizeN * sizeof(int));    
}

首先为结构本身分配内存

atype = malloc(sizeof(A))

在按值传递指针时,您需要 return 将 atype 的地址传递给您的 main 函数,否则您在 allocateStruct 中所做的更改将无法在 main 中访问,并且还会导致内存泄漏。如果您正在 returning 地址,则无需将类型作为参数传递。

A* allocateStruct(int sizeN){
    A* atype;
    atype = malloc(sizeof(A));
    aType->x = malloc(sizeN * sizeof(int));   
    aType->y = malloc(sizeN * sizeof(int)); 
    return atype;
}

并在主要部分

atype = allocateStruct(5);

此外,您不需要在 C 中显式进行类型转换,malloc return 是一个空指针,它可以分配给任何类型。并且为了完整性,这样你就不会在 main 的末尾导致内存泄漏,只需释放你分配的所有内存。

free(atype->x);
free(atype->y);
free(atype);