c - char *str[ ] pass by reference not working -


i passing char *str[] in function , adding contents in main function values unchanged.

from main calling lettercombinations function , calls function in editing valuees of char * str[] wwhihc changed there not reflected in letter combinations function

please me why not working

help(char *str[],char* curr,int index,char* digits,char** a,int *k)         {             if(strlen(curr)==strlen(digits))             {                 printf("%d",*k);                  str[*k]=(char*)malloc(strlen(digits)+1);                  str[*k]=curr;                 printf("%s %s %d\n",curr,str[*k],*k);                  *k=*k+1;                  return ;             }              int i;              char* loop=a[digits[index]-'0'];              int l=strlen(loop);             for(i=0;i<l;i++)             {                 curr[index]=loop[i];                  help(str,curr,index+1,digits,a,k);                 curr[index]='\0';             }         }   char** lettercombinations(char* digits, int* returnsize) {             char *str[100];               int i=0;             char* curr=malloc(sizeof(strlen(digits)+1));             char** a=(char**)malloc(10*sizeof(char*));           int siz=0;             a[0]="";             a[1]="";             a[2]="abc";             a[3]="def";             a[4]="ghi";             a[5]="jkl";             a[6]="mno";             a[7]="pqrs";             a[8]="tuv";             a[9]="wxyz";              help(str, curr, 0, digits,a,&siz);              printf("  %d",siz);             for(i=0;i<siz;i++)             {                 printf(" s   %s",str[i]);             }            // *returnsize=siz;             return str;             } 

if compile code should see warnings such as:

warning c4172: returning address of local variable or temporary warning c4100: 'returnsize' : unreferenced formal parameter 

returning address of local variable or temporary warning explains behaviour.

in code:

char** lettercombinations(char* digits, int* returnsize) {     char *str[100];    ...     return str; } 

you create array on stack, str. when return lettercombinations, variable goes out of scope , stack memory location gets cleaned up. ie memory address used str no longer valid.

you change caller passes in own char* variable fix issue. alternatively, malloc str , when return function, memory location still exists. caller have free memory location - messy.

after fixing ... move onto next bug.

the next thing notice in function have:

if (strlen(curr) == strlen(digits)) 

but curr not initialised. fix next. move onto next bug.

you should step through each line thinking through how variables populated in each line.


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -