c - compiler complaining when returning char pointer array -


i'm trying return array of char pointers compiler doesn't seem it.

char*[] get_multiple(int x) {     char *tmp[x];     int i;     (i=0;i<x;i++)         tmp[i]=strdup("abc");     return tmp; } 

the compiler errors out following:

error: expected identifier or '(' before '[' token  

on line 1

any idea why compiler doesn't , how fix it?
(i know can alternatively pass in structure caller store return pointers, want avoid doing that)

allow me add @lidong guo's answer (quoted below)

you can't create array :char * tmp[x],since x known runtime!

use char **tmp = malloc(x*sizeof(char *)); instead

by looking @ code, can see have misunderstood either array label tmp represents or tmp located.

when allocate variable (or array of static size) in function, stored on stack, in current stack frame. stack frame destroyed/freed function returns , should not using/referencing memory more!!!

tmp label represents memory address @ tmp array located. on stack when function returns no longer valid pointer!

forgive me if know judging terminology suspect might not.

in c can not assign arrays other arrays!

int array1[10], array2[10];  // ... put values array 1 ...  array2 = array1; // illegal! not copy array 

similarly, if return tmp returning address, not array if assigning variable should copying instead of assigning it!

hence c not allow return array , should returning pointers instead.

but when return pointer tmp in trouble because of way trying allocate (on stack) @lidong guo suggested allocate on heap can live after function returns. however, means need remember free memory!

so rewrite of function using @lidong guo's code like

char** get_multiple(int x) {     char **tmp = malloc(x * sizeof(char*));     int i;     (i=0;i<x;i++)         tmp[i]=strdup("abc");     return tmp; } 

and hypothetical main use so:

int main() {     char** multiple7;      multiple7 = get_multiple(7);      // stuff on multiple 7     free(multiple7[3]);      // more stuff ...      // don't forget free multiple7 array memory     free(multiple7);      return 0; } 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -