I'm having trouble trying to allocate a 2d array of char* and return it from a function.
//my return type needs to change to something like (char*)[]?
char **readData( size_t numRows, size_t numCols )
{
//I think this needs to chage to something like this:
//char* (*data)[numRows] = malloc(sizeof(char*) * numCols );
char **data = malloc( sizeof(char*) * numRows * numCols );
for( size_t r=0; r < numRows; ++r ) {
for(size_t c=0; c < numCols; ++c) {
data[r*numRows+c] = strdup( getString() );
//I'd like this to be:
//data[r][c] = strndup( getString() );
}
}
return data;
}
int main()
{
size_t rows = 5;
size_t cols = 7;
char **data = readData( rows, cols );
if( data != NULL ) {
for( int r=0; r < rows; ++r ) {
for( int c=0; c < cols; ++c ) {
printf( "[%i][%i] = %s\n", r, c, data[r*rows+c] );
free(data[r*rows+c]);
data[r*rows+c] = NULL;
//I'd really like this to be:
//printf( "[%i][%i] = %s\n", r, c, data[r][c] );
//free(data[r][c]);
//data[r][c] = NULL;
}
}
free(data);
data = NULL;
}
return 0;
}
I have two questions:
1) The above code is broken somehow. The printf prints NULLs when I wouldn't expect it to. I must be screwing up the indexing someplace.
2) I believe with C99 I can use the more familiar data[][]
notation to index the 2d array of pointers. I have the changes in comments in the above code but I don't know what to set the return type of the function as. How can I change my program to use the data[][]
notation? It may not be possible since I do not know either array dimension at compile time.
I've looked at the following stack overflow questions but still can't seem to get my head around it: Why can't we use double pointer to represent two dimensional arrays?
How to return a two-dimensional pointer in C?
Why can't we use double pointer to represent two dimensional arrays?