void parseFile(unsigned *line, char **matrix)
{
FILE *fp;
char buff[cols];
char ***ptr;
ptr = &matrix;
fp = fopen("cazino_heist_maffs.csv", "r");
if (fp == NULL)
{
// return 1;
}
int i = 0;
while (fgets(buff, 255, (FILE *)fp) != NULL)
{
printf("%d: %s\n", *line, buff);
for (i = 0; buff[i] != '?'; i++)
{
matrix[*line][i] = buff[i];
}
(*line)++;
char **tmp;
tmp = realloc(matrix, sizeof(matrix) * ((*line) + 1));
if (tmp == NULL)
{
printf("fail");
// return 1;
}
matrix = tmp;
for (int i = *line; i < (*line) + 1; i++)
{
matrix[i] = malloc(100 * sizeof(char *));
}
}
fclose(fp);
}
So I have this method to read from a file and fill a pointer to arrays. The function works inside the method however when I go back to main the matrix isn't filled.
printf("ALL: \n");
for (unsigned i = 0; i < *line; i++)
{
for (unsigned j = 0; matrix[i][j] != '='; j++)
{
printf("%c", matrix[i][j]);
}
printf("\n");
}
If I put this inside the function it works fine but if I put it in the main it doesn't work.
char **matrix;
matrix = malloc2dArray(rows, cols);
//
parseFile(&line, matrix);
Also this is how I call the method. I assume I pass my matrix by value instead of reference however I am not sure how to do it with the double pointer. Any help?
To pass an variable to a function "by reference", you pass its address. You have a char **
, which means its address has type char ***
. So make that the parameter type for the function.
void parseFile(unsigned *line, char ***a_matrix)
{
char **matrix = *a_matrix;
// do stuff
*a_matrix = matrix;
}
And pass in the address:
parseFile(&line, &matrix);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.