c - Returning a character array from a function prints garbage values but prints fine in the function? -
#include<stdio.h> #include <string.h> char *generate(char a[],int s,int e,char r[]) { if(s>e){ printf("%s\n ",r); //prints correct value "rempd" here return r; } int i,asci[128]={0}; for(i=s;i<=e;i++) if(asci[a[i]]==1) break; else asci[a[i]]=1; char t[i-s]; t[i-s]='\0'; for(i=i-1;i>=s;i--) t[i-s]=a[i]; if(r==0||strlen(t)>strlen(r)) return generate(a,s+1,e,t); else return generate(a,s+1,e,r); } int main() { char a[]="prrempd"; printf("largest unique string:\n%s",generate(a,0,strlen(a)-1,null)); // prints garbage value here }
this function used return largest unique substring within string. when character array returned, returns garbage value.
char t[i-s];
allocated on stack , gets deallocated when return generate()
.
if want live beyond call generate()
must use heap or other allocation method.
Comments
Post a Comment