[英]Access to field results in dereference of a null pointer in C
這個問題與 C Programming Language: I get error: Access to field 'x' results in a dereference of null pointer 有關
#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] );
}
您尚未將 memory 分配給該結構,但您正在訪問它的成員
void allocateStruct(int sizeN, A* aType) {
aType->x = (int*)malloc(sizeN * sizeof(int));
aType->y = (int*)malloc(sizeN * sizeof(int));
}
先將 memory 分配給結構體本身
atype = malloc(sizeof(A))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.