Reputation: 421
I have a function that's supposed to merge 2 strings and return the resultant longer string. The string appears to be successfully merged in the function, but when returned the information is lost. 'output' in function contains the merged string, and this value is supposed to be returned.
The mergedString does not print in main, but prints in the function. Why? How to make it work?
main () {
char *mergedString = mergeStrings( frags[maxOverlapArrPos1], frags[maxOverlapArrPos2], maxCharOverlap);
printf ("mergedStringInMain is %s\n", mergedString);
}
char * mergeStrings(char * string1, char * string2, int overlapCharSize){
int overlapStartPosition = strlen(string1) - overlapCharSize;
char output[] = "";
if (strlen(string2)>overlapCharSize){
strncat(output, string1, overlapStartPosition);
strncat(output , string2, strlen(string2));
}
printf ("mergedStringInFunction is %s\n", output);
return output;
}
The output is:
mergedString is abcdefg
mergedString is ?
Upvotes: 1
Views: 150
Reputation: 409452
You have two instances of undefined behavior in your code: The first is that you use an array one character long and writes more than one character into it. The second is that you return a pointer to a local variable.
Upvotes: 5