WickSec WickSec - 24 days ago 5x
C Question

How to return a char** in C

I've been trying for a while now and I can not seem to get this working:

char** fetch (char *lat, char*lon){
char emps[10][50];
//char** array = emps;
int cnt = -1;

while (row = mysql_fetch_row(result))
char emp_det[3][20];
char temp_emp[50] = "";
for (int i = 0; i < 4; i++){
strcpy(emp_det[i], row[i]);

if ( (strncmp(emp_det[1], lat, 7) == 0) && (strncmp(emp_det[2], lon, 8) == 0) ) {

for (int i = 0; i < 4; i++){
strcat(temp_emp, emp_det[i]);
if(i < 3) {
strcat(temp_emp, " ");
strcpy(emps[cnt], temp_emp);

return array;

Yes, I know array = emps is commented out, but without it commented, it tells me that the pointer types are incompatible. This, in case I forgot to mention, is in a char** type function and I want it to return emps[10][50] or the next best thing. How can I go about doing that? Thank you!


What you're attempting won't work, even if you attempt to cast, because you'll be returning the address of a local variable. When the function returns, that variable goes out of scope and the memory it was using is no longer valid. Attempting to dereference that address will result in undefined behavior.

What you need is to use dynamic memory allocation to create the data structure you want to return:

char **emps;
emps = malloc(10 * sizeof(char *));
for (int i=0; i<10; i++) {
    emps[i] = malloc(50);
return emps;

The calling function will need to free the memory created by this function. It also needs to know how many allocations were done so it knows how many times to call free.