For starters this memory allocation using the magic number 10
makes the function unsafe.
char *str=(char*)malloc(sizeof(char)*10);
In these while loops
while( *string != '\0')
{
*(str) = *(string++);
printf("char is %c\n", str[n++]);
str++;
}
while( *sub != '\0')
{
*(str) = *(sub++);
printf("char is %c\n", str[n++]);
str++;``
}
the pointer str
is being changed (incremented). So after the loops it points to a garbage.
And you forgot to include in the result string the terminating zero character '\0'
.
The function can be defined the following way
char * addsubstring( const char *s1, const char *s2 )
{
size_t n1 = strlen( s1 );
char *result = malloc( n1 + strlen( s2 ) + 1 );
if ( result != NULL )
{
memcpy( result, s1, n1 );
strcpy( result + n1, s2 );
}
return result;
}
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * addsubstring( const char *s1, const char *s2 )
{
size_t n1 = strlen( s1 );
char *result = malloc( n1 + strlen( s2 ) + 1 );
if ( result != NULL )
{
memcpy( result, s1, n1 );
strcpy( result + n1, s2 );
}
return result;
}
int main(void)
{
char *p = addsubstring( "Hello ", "World!" );
if ( p ) puts( p );
free( p );
return 0;
}
The program output is
Hello World!
If you may not use standard C string functions then the function can be defined as it is shown in the demonstrative program below
#include <stdio.h>
#include <stdlib.h>
char * addsubstring( const char *s1, const char *s2 )
{
size_t n = 0;
while ( s1[n] ) ++n;
while ( s2[n] ) ++n;
char *result = malloc( n + 1 );
if ( result != NULL )
{
char *p = result;
while ( *s1 ) *p++ = *s1++;
while ( ( *p++ = *s2++ ) );
}
return result;
}
int main(void)
{
char *p = addsubstring( "Hello ", "World!" );
if ( p ) puts( p );
free( p );
return 0;
}
The program output is the same as shown above
Hello World!