简体   繁体   中英

C concat two small strings to one larger string

I am trying to create a program that will concatenate two strings together. My code creates a char[] that is strcat -ed into by two strings. The result is confusing garbage. Any idea what's happening? I would imagine that the char[] is already filled with garbage when I try to concat it, but I'm not sure.

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

int main(){
    char* s1 = "this";
    char* s2 = "that";
    char s3[9];

    int i;

    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
    strcat(s3, s1);
    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
    strcat(s3, s2);
    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
}

Output:

@



@
t


@
t

You either have to set s3[0] = '\\0'; or you must use strcpy for the first one.

s3[0] = '\\0';

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

int main(){
    char* s1 = "this";
    char* s2 = "that";
    char s3[9];
    int i;

    s3[0] = '\0';

    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
    strcat(s3, s1);
    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
    strcat(s3, s2);
    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
}

strcpy

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

int main(){
    char* s1 = "this";
    char* s2 = "that";
    char s3[9];

    int i;

    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
    strcpy(s3, s1);
    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
    strcat(s3, s2);
    for(i = 0; i < 4; i++){
        printf("%c\n", s3[i]);
    }
}

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