Fechang Fuchang
Fechang Fuchang

Reputation: 151

String concatenation in c, not using function

I am trying to concatenate strings not using function in Dev-C++ compiler. So my code is:

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

int main(void){

char string1[] = "water", string2[] = "melon";
int i=0,j=0;

while(i++, string1[i] != 0);
for(j=0;string2[j] !=0; i++){

    string1[i] = string2[j];
    j++;
}



printf("%s",string1);

getch();
return 0;

}

The output i get is: watermelp. Where's the problem?

Note: I couldn't use *string1 and *string2 instead of string1[] and string2[]. As i have to use const (because of Wwrite-strings warning) while declaring them. And this gives an error while concatenating as an assignment of read-only location. Is there any solution of it?

Upvotes: 1

Views: 80

Answers (1)

R Sahu
R Sahu

Reputation: 206717

You are seeing the symptoms of undefined behavior. You are writing over memory that you are not supposed to.

When you use:

char string1[] = "water", string2[] = "melon";

string1 and string2 have enough memory to hold "water" and "melon", respectively.

Use

char string1[100] = "water", string2[] = "melon";

With that, string1 will have enough memory to hold "watermelon".

Suggestion for improvement:

Instead of

while(i++, string1[i] != 0);

Use

while ( string1[i] != 0 ) i++;

The second form is not only more readable, it also avoids an error. The first form will be wrong if string1 is an empty string.

Upvotes: 2

Related Questions