This is a program to concatenate strings using malloc
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char *sconcat(char *ptr1,char *ptr2);
void main()
{
char string1[20],string2[20],*ptr;
clrscr();
printf("enter string 1: ");
gets(string1);
printf("enter string 2: ");
gets(string2);
ptr=sconcat(string1,string2);
printf("output string : %s",ptr);
getch();
}
char *sconcat(char *ptr1,char *ptr2)
{
int len1,len2,i,j;
char *ptr3;
len1=strlen(ptr1);
len2=strlen(ptr2);
ptr3=(char *)malloc((len1+len2+1)*sizeof(char));
for(i=0;ptr1[i]!='\0';i++)
ptr3[i]=ptr1[i];
j=i;i=0;
for(;ptr2[j]!='\0';j++,i++)
ptr3[j]=ptr2[i];
ptr3[j]='\0';
return(ptr3);
}
output:
enter string 1 : this program does
enter string 2 : not give output
output string : this program does
What correction is needed to concatenate strings. When I use char string1[20],string2[20],*ptr;
after void main()
,
output:
enter string 1 : is this
enter string 2 : correct ?
output string : correct? ?