gpt4 book ai didi

c - 将指向结构数组的指针传递给 malloc 的函数

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:30 24 4
gpt4 key购买 nike

我环顾四周,找到了有关如何使用指针表示法为二维数组正确分配内存的答案,并且我找到了如何将二维指针数组正确传递给函数的方法,但我似乎无法结合这两个步骤。

所以从逻辑上讲,我要做的是分配一个指向结构的指针数组。似乎失败的是尝试分配内存

到目前为止我的代码:

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打印数据失败了。

最佳答案

您正在正确分配结构的二维数组。

但您只是读取结构的一维数组。 (例如 array[i]->tax)

要读取结构的二维数组,您需要 2 个 for 循环

for (int i = 0; i < size; i++) {
for (int j=0; j< size; j++) { // in your case you have a size*size array,
fscanf(fptr, "%d,%d,%f", array[i][j]->tax, array[i][j]->savings, array[i][j]->salary);
}
}

您需要决定是需要一维数组还是二维数组。

关于c - 将指向结构数组的指针传递给 malloc 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com