I’m passing a pointer to a pointer (**resultSet) to my MySQL function.
Here’s an excerpt on how I copy the MySQL data from within the function:
int
getItems(char * cmd, char **resultSet)
{
...
MYSQL initialisations and set-up
...
resultSet = malloc(sizeof(char)*(int)mysql_num_rows);
while((row = mysql_fetch_row(result)))
{
for (i=0 ; i < mysql_num_fields(result); i++)
{
printf("%i: \t", i);
resultSet[counter] = malloc(sizeof(char)*strlen(row[i])+1);
strcpy(resultSet[counter], row[i]);
printf("%s\n", resultSet[counter]);
}
printf("---------------------\n");
counter++;
}
...
MYSQL cleaning up
...
return 0;
}
Calling it in main with
getItems(cmd, resultSet);
From within my getItems function this
printf("%s\n", resultSet[0]);
seems to work.
However, if I try to access it from outside my function I get a segmentation fault. Why is this?
If you want to use resultSet as a return parameter, you need to make the function signature
and use it in the function like
The function call could look like
Better and simpler is probably to leave it as it is and make the allocation before the function call.