[Solved] Program Crashed (String Manipulation) [closed]


Perhaps like this. Note that string concatenation cannot be done on simple char types.

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

int main (void) {
    char s1[] = "stack";                            // skipped the string inputs
    char s2[] = "overflow";
    char str[120];
    size_t i;                                       // var type returned by `strlen`
    size_t index = 0;
    size_t leng1 = strlen(s1);
    size_t leng2 = strlen(s2);
    size_t leng = leng1 <= leng2 ? leng1 : leng2;   // ternary operation to get min length
    if(leng == 0 || leng * 3 > sizeof str)
        return 1;                                   // will not fit output string
    for(i = 0; i < leng; i++) {                     // note `<=` changed to `<`
        str[index++] = s1[i];                       // buiuld the output string
        str[index++] = s2[i];
        str[index++] = ' ';                         // pad string
    }
    str[index - 1] = '\0';                          // terminate string
    printf("%s\n", str);
    return 0;
}

Program output:

so tv ae cr kf

7

solved Program Crashed (String Manipulation) [closed]