简体   繁体   中英

Concatenate two string program not giving correct output

#include<stdio.h>
char * sstrcat(char*,char*);
void main() {
    char *c;
    char s[100] = "abcde";
    char t[] = "fghi";
    c = sstrcat(s,t);
    printf("%s",c);
}

char* sstrcat(char *s,char *t) {
    char* temp = s;
    while(*s++ != '\0');
    while((*s++ = *t++) != '\0');

    return temp;
}

Above written code I am getting output abcde but expected output is concatenation of string s and t .

Please help me to figure out what mistake I am doing? thanks.

This line

while(*s++ != '\0');

will increment s after the comparison has been made, leaving '\0' , which is a string terminator in your array.

If you can use a debugger you will find that all values are in your array, its just that printf will stop at '\0'

Just move your string iterator back one char due to '\0' (after you execute while(*s++;= '\0'); ) and that fixes your code.


Explanation:

Your s string is "abcde\0" . After the first while loop, the iterator will be at '\0' . If you leave it there you will concatenate both strings obtaining the result "abcde\0fghi\0" which prints "abcde" due to the first '\0' .

Instead, if you move back the s string iterator one position with ( s-- ) you will have this string as result "abcdefghi\0" which prints the string as you expect.

Fixed Code:

#include<stdio.h>

char * sstrcat(char*,char*);

void main() {
    char *c;
    char s[100] = "abcde";
    char t[] = "fghi";
    c = sstrcat(s,t);
    printf("%s\n",c);
}

char* sstrcat(char *s,char *t) {
    char* temp = s;
    while(*s++ != '\0');
    s--;
    while((*s++ = *t++) != '\0');

    return temp;
}

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