【发布时间】:2019-09-26 03:18:12
【问题描述】:
我环顾四周,找到了有关如何为带有指针表示法的二维数组正确分配内存的答案,并且我发现了如何正确地将二维指针数组传递给函数,但我似乎无法结合两个步骤。
所以从逻辑上讲,我想要做的是分配一个指向结构的指针数组。似乎失败的是尝试分配内存
到目前为止我的代码:
typedef struct {
int tax, savings;
float salary;
} employee;
int readRecordFile(char* filename, Record*** array);
int main(void) {
employee** array;
int size;
char* file = "money.csv";
size = readRecordFile(file, &array);
FILE* fptr;
fptr = fopen(file, "r");
//Read the file into the the array
for (int i = 0; i < size; i++) {
fscanf(fptr, "%d,%d,%f", array[i]->tax, array[i]->savings, array[i]->salary);
}
fclose(fptr);
for (int i = 0; i < size; i++) {
printf("%d, %d, %f\n", array[i]->tax, array[i]->savings, array[i]->salary);
}
return 0;
}
int readRecordFile(char* filename, employee*** array) {
//Function to open the file, malloc and initialize 2d arrays
//Open the file
FILE* fileptr;
fileptr = fopen(filename, "r");
if (fileptr == NULL) {
printf("Failed to open file");
exit(-1);
}
//Read first line of file (the size) and store to an int
int n;
fscanf(fileptr, "%d", &n);
//Initial malloc for the array of pointers
**array = malloc(n * sizeof(employee*)); //This is the line that throws the exception
//Malloc for each pointer in the array of pointers
for (int i = 0; i < n; i++) {
*(array+i) = malloc(sizeof(employee));
}
//Close the file and return the size of the file
fclose(fileptr);
return n;
}
我尝试在函数中构建一个单独的结构指针,然后将常规指针设置为它
//Initial malloc for the array of pointers
employee **tester = malloc(n * sizeof(employee*));
//Malloc for each pointer in the array of pointers
for (int i = 0; i < n; i++) {
*(tester+i) = malloc(sizeof(employee));
}
array = tester;
此方法似乎可以修复 malloc 问题,但 main 中的数据打印失败。
【问题讨论】:
标签: c