#include <stdio.h>
#include <string.h>
char* string(char *str);
int main()
{
printf("%s\n ",string(" in this method "));
getchar();
return 0;
}
char string(char *str4) // the char should be char*
{
char str[25] = "How";
char str2[25] = " do I ";
char str3[25] = " return a string";
strcat(str,str2); //append str2 to str and return str
return strcat(str,str3); // you are returning the addr of local variable
// whose scope is limited to this function.
} Dont return the addr of a local variable since local vars of a function are placed on the stack and are destroyed when the function returns.
Better pass the string which you want to be modified to the function.
Something like this:
#include <stdio.h>
#include <string.h>
char* my_string (char *src, char* dest);
int main()
{
char str[25] = {'\0'} ;
printf("%s\n ",my_string(" in this method ", str));
getchar();
return 0;
}
char* my_string(char *src, char* dest)
{
char str1[25] = "How";
char str2[25] = " do I ";
char str3[25] = " return a string";
strcat(dest,str1); //append str2 to str and return str
strcat(dest,str2);
strcat(dest,str3);
return dest ;
}
Hope it helped, bye.
~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734