简体   繁体   中英

appending the strings to be one string in C

i am trying to combine 2 strings to be one without using strcat function, but get some errors, anyone can help me?

#include<stdio.h>
#include<conio.h>
#include<string.h>

char str[200];
char  *combine(char *str1,char *str2){
    int i,j ,k;

    while (str1[i]) str[k++] = str1[i++];
    while (str2[j]) str[k++] = str2[j++];
    str[k]= '\0';
    return str;

}
void main(void){
    char str1[100], str2[100];
    printf("string1:"); gets(str1);
    printf("string2");gets(str2);
    printf("combination of 2 strings: %s",combine(str1,str2));
getch();    
}

i,j,k have garbage value as it is not initilized change your combine function a bit

char  *combine(char *str1,char *str2){
   int i=0,j=0 ,k=0;

   while (str1[i]) 
       str[k++] = str1[i++];
   while (str2[j]) 
       str[k++] = str2[j++];
   str[k]= '\0';
   return str;

 }

Lots of problems in your code. conio.h is non-standard, use getchar() which is there in stdio.h already instead of getch() . main retuns an int , use fgets for buffer safety also your variables (i,j,k) were not initialized in the combine method. Here is the working code:

#include<stdio.h>
#include<string.h>

    char str[200];

char *combine(char *str1,char *str2)
{
    int i=0,j=0 ,k=0;

    while (str1[i]) str[k++] = str1[i++];
    while (str2[j]) str[k++] = str2[j++];
    str[k]= '\0';
    return str;

}

int main(void)
{
    char str1[100], str2[100];
    printf("string1:");
    fgets(str1,100,stdin);
    printf("string2");
    fgets(str2,100,stdin);
    printf("combination of 2 strings: %s",combine(str1,str2));
    return 0;
}

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