The function tries to concatenate two strings in the reverse order and store the result in a character array.
However there is a problem because there is passed a string literal as the destination array to the function
char* string3="\0";
that may not be changed. Any attempt to change a string literal results in undefined behavior.
Instead you should write for example
char string3[8];
That is you need to pass a large enough array that can accommodate two concatenated strings: string1
and string2
.
Also the function should be declared at least like
char* f(const char *p1, const char *p2, char *p3);
That is the passed string except of the result array are not changed within the function.
Here is your updated program. I changed the order of parameters in the function and renamed it.
#include <stdio.h>
char * reversed_concatenation( char *s1, const char *s2, const char *s3 )
{
char *p1 = s1;
const char *p2 = s2;
while ( *p2 ) ++p2;
while ( p2 != s2 )
{
*p1++ = *--p2;
}
const char *p3 = s3;
while ( *p3 ) ++p3;
while ( p3 != s3 )
{
*p1++ = *--p3;
}
*p1 = '\0';
return s1;
}
int main( void )
{
const char *string1 = "abcd";
const char *string2 = "efg";
char string3[8];
puts( reversed_concatenation( string3, string1, string2 ) );
}
The program output is
dcbagfe
In this function for example this for loop
const char *p2 = s2;
while ( *p2 ) ++p2;
finds the end of the first concatenated string and then this for loop
while ( p2 != s2 )
{
*p1++ = *--p2;
}
writes the string in the reverse order in the result character array.
The same operations are done with the second concatenated string.