简体   繁体   中英

concatenating strings using malloc

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? ?

The test in your second for loop is incorrect; it should be ptr2[i] != '\\0' , not ptr2[j] != '\\0' .

Several remarks on the code:

  • Don't cast the return value of malloc .
  • sizeof(char) is 1 by definition, so multiplying by sizeof(char) only makes the code harder to read.
  • Declare the parameters of sconcat as const char * , since they're not modifying the strings they receive.
  • malloc can return NULL; you must handle that case in your program, for example by displaying an error message and exiting.
  • gets is unsafe and will crash your program if the user enters more characters than were allocated. Replace gets(string) with fgets(string, sizeof(string), stdin) , and getting rid of the trailing newline.
  • clrscr() and getch() , as well as the infamous <conio.h> header, are not standard C and are non-portable; avoid them in simple programs like this one.

You can more simply use strcat

printf("enter string 1: ");
gets(string1);

printf("enter string 2: ");
gets(string2);

strcat(string1,string2);

It would, however, change string1 so you might want to use strcpy too (to copy string1 to another string and then return it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM