這個問題與 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] );
}
uj5u.com熱心網友回復:
您尚未為該結構分配記憶體,但您正在訪問它的成員
void allocateStruct(int sizeN, A* aType) {
aType->x = (int*)malloc(sizeN * sizeof(int));
aType->y = (int*)malloc(sizeN * sizeof(int));
}
首先為結構本身分配記憶體
atype = malloc(sizeof(A))
當您通過值傳遞指標時,您需要將 atype 的地址回傳給您的 main 函式,否則您在 allocateStruct 中的更改將無法在 main 中訪問,并且還會導致記憶體泄漏。如果您回傳地址,則不需要將 atype 作為引數傳遞。
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 回傳一個 void 指標,它可以分配給任何型別。并且為了完整性,這樣您就不會在 main 結束時導致記憶體泄漏,只需釋放您分配的所有記憶體即可。
free(atype->x);
free(atype->y);
free(atype);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/409915.html
標籤:
上一篇:遞回中的指標未按預期作業
