Home > Mobile >  Failing to return a string from a function
Failing to return a string from a function

Time:01-20

I cant get it to work. I build a string and cant to return it, I tried to tweak with pointers but it didnt work too. Details in the code:

char* replace(const char* sSource, unsigned int nSearch, unsigned int nReplace)
{
   char str[strlen(sSource) 1];

   \\filling str and putting '\0' at the end......

   return str;  // At this point str = "abgde3"  TRYING TO PRINT STR INSIDE THE FUNCTION WORKS !
}

int main()
{
    printf("%s", replace("A39a933Ab",93,314));
    return 0;
}

CodePudding user response:

U have to return pointer, not an array. Like here:

char* replace(const char* sSource, unsigned int nSearch, unsigned int nReplace)
{
   char str[strlen(sSource) 1];

   return &str; //Added & to get pointer to variable
}

Also, u should not return pointer to local var, so allocate memory for one, and return it.

char* replace(const char* sSource, unsigned int nSearch, unsigned int nReplace)
{
   char * str = (char *)malloc(strlen(sSource) 1);

   return str;
}

You must to clean allocated memory by free(pointerToArray)

  •  Tags:  
  • Related