简体   繁体   中英

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?

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.

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