搜索了一個小時左右。我想我最好在這裏發佈這個問題。爲什麼初始化結構時會出現段錯誤?
我簡化了代碼。段錯誤在函數initMyStruct
中。
#include "stdlib.h"
typedef struct {
int * arr1;
int * arr2;
} myStruct;
void allocMyStruct (myStruct * a, int num) {
a = malloc(sizeof(myStruct));
a->arr1 = malloc(10*sizeof(int));
a->arr2 = malloc(10*num*sizeof(int));
}
void initMyStruct (myStruct * a, int num) {
int i;
for (i = 0; i < 10; i++) a->arr1[i] = 0;
for (i = 0; i < 10*num; i++) a->arr2[i] = -1;
}
void freeMyStruct (myStruct * a, int num) {
int i;
for (i = 0; i < 10; i++) free(a->arr1);
for (i = 0; i < 10*num; i++) free(a->arr2);
free(a);
}
int main (void) {
int num = 3;
myStruct * a;
allocMyStruct (a, num);
initMyStruct (a, num);
freeMyStruct (a, num);
return 1;
}
無關,但爲什麼你的'main'函數返回1?如果程序返回1,則表示某種AFAIK失敗。 std lib有宏的定義:'#define EXIT_SUCCESS 0'和'#define EXIT_FAILURE 1' ... –