I tried to write a programme which copies the first k char from a string s1 and then concatenates the result with the rest of string s2 starting from a position i
then concatenates the rest of s1 in the result. Yet I had some problems with strncpy
.
It shows some weird characters in console like @.
Here's my code:
char* strninsert(char *s1, char *s2, int k,int i)
{
int n=strlen(s1)+strlen(s2)+10; // if i put for exemple 1000 it works
char *result=(char*)malloc(n*sizeof(char));
result[0]='\0';
strncpy(result,s1,k);
strcat(result,(s2+i));
strcat(result,(s1+k));
puts(result);
return(result);
}
int main()
{
int lens;
printf("size string 1 ");
scanf("%d",&lens);
char *s=(char*)malloc((lens+1)*sizeof(char));
getchar();
fgets(s,lens+1,stdin);
int lenx;
printf("enter size string 2 ");
getchar();
scanf("%d",&lenx);
char *x=(char*)malloc((lenx+1)*sizeof(char));
getchar();
fgets(x,lenx+1,stdin);
int lentemp=lenx+lens;
char *temp=(char*)malloc((lentemp+1)*sizeof(char));
temp=strninsert(s,x,2,3);
puts(temp);
return(0);
}
It shows me weird characters after the strncpy
instruction like for example
poes@<line
.