I have a 2d array of pointers (to strings)
char *result[7000][14];
I want to write a function that returns the first string in each “row”.
Here’s what I tried:
char *getRownames (int a, int b, char *matrix[a][b])
{
char *rownames[a];
for(int i=0;i<a;i++){
rownames[i] = malloc(strlen(matrix[i][0])+1);
strcpy(rownames[i],matrix[i][0]);
}
return *rownames;
}
And then
char *names = getRownames(7000, 14, result);
I get an error that says conflicting types for getRowNames. Still getting used to C and having to allocate my own memory.
You have a few things going on here.
Function declarations/prototypes need to have fixed sizes for their arrays & matrices.*
char *getRownames (int a, int b, char *matrix[a][b])won’t work because the compiler doesn’t know
aorbwhen compiling your program. It would need to bechar *getRownames (int a, int b, char *matrix[7000][14])if you know the array will be that size. Then you don’t need
aorbat all. If you want to be able to pass matrices of varying sizes to the function, that’s a different matter entirely.*(Note the compiler allows you to leave out the first dimension of arrays:
char *matrix[][14]orchar *array[])Next, you’ll need to cast the return value from malloc to a char*, as malloc() returns void*:
rownames[a] = (char*)malloc(strlen(matrix[i][0])+1);By the way, it should be
rownames[i]in your loop. 🙂 Sinceiis your loop variable.And last, it looks like you want to return an array of char*, but
return *rownameswill send back just the first value in the array. Again, if you know the size the array will be, it’s easier to pass an existing array to the function and have it fill in the values. Otherwise you have to malloc the array to return.