Pass by reference 2D dynamically allocated double array in C
I'm trying to convert my string into a dynamic array of doubles. Each space of my string represents a column, each ";" represents a new row. When this code runs, it only works for when *F[0][col]. When it gets to *F[1][col] it gives me the error "Unhandled exception at 0x00e4483c in CCode.exe: 0xC0000005: Access violation reading location 0xcccccccc." Anyone know why?
void main(void) {
double **F = NULL;
F = malloc(row * sizeof (double *));
for (m=0; m < row;m++) {
F[m] = malloc(col * sizeof(double ));
}
FParser(string, &F);
for (m=0;m<rowF;m++)
free(F[m]);
free(F);
}
void FParser(char string[256], double ***F) {
while (dummyChar_ptr != NULL) {
dummyChar_ptr = strtok(dummyChar开发者_如何学编程_ptr," ");
while ((dummyChar_ptr) != NULL) {
*F[row][col] = atof(dummyChar_ptr);
dummyChar_ptr = strtok(NULL," ");
col++;
}
col=0;
row++;
strcpy(dummyChar,string);
dummyChar_ptr = strtok(dummyChar,";");
for (x=0;x<row;x++)
dummyChar_ptr = strtok(NULL,";");
}
//example String: 1 0.1 0 0; 0 1 0 0; 0 0 1 0.1; 0 0 0 0.1
[]
has a higher precedence than unary *
in C, so *F[row][col]
is actually *(F[row][col])
, and you're indexing into the wrong memory location.
Try (*F)[row][col])
.
Incidentally, there's no reason for FParser
to take a double***
anyway. F
is already a pointer; just pass that. The only reason you'd need to use an extra level of indirection is if FParser
needed to modify what main()
's F
points to.
Other miscellaneous bits of advice:
- Check whether
malloc
succeeded. - Avoid global variables.
- Don't use
strcpy
unless you've checked that the source string won't overflow the destination buffer. - The function parameter
char string[256]
doesn't actually guarantee that the input argument is an array of 256 (or more) elements, so IMO it's kind of pointless and might as well bechar* string
.
精彩评论