0

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();    
}
user3376115
  • 59
  • 1
  • 1
  • 6

2 Answers2

1

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;

 }
KARTHIK BHAT
  • 1,410
  • 13
  • 23
1

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;
}
Sadique
  • 22,572
  • 7
  • 65
  • 91