Home > Enterprise >  How to combine 2 arrays without using strncat?
How to combine 2 arrays without using strncat?

Time:09-29

I currently try to combine 2 arrays without using strncat. The following code doesnt work and the problem lies in one of the for loops. I guess that some of these boundaries are wrong, but I'm not capable of finding the mistake:

#include <stdio.h>
int main() {
    char text1[] = {"Hello"};
    char text2[] = {", how are you?"};
    char result[100];
    int count1 = strlen(text1);
    int count2 = strlen(text2);
    printf("%d\n", count1);
    printf("%d\n", count2);
    
    for(int i = 0; i<count1; i  ) {
        result[i] = text1[i];
    }
    
    for(int k = 0; k<count2; k  ) {
        result[k 1 count1] = text2[k];
    }
    
    for(int j = 0; j<count1 count2; j  ) {
        printf(" %s", result[j]);
        
    }    
    
    return 0;
}

CodePudding user response:

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

int main() {
    char text1[] = "Hello"; //correct way to initialize string
    char text2[] = ", how are you?";
    char result[100];
    int count1 = strlen(text1);
    int count2 = strlen(text2);

    printf("%d\n", count1);
    printf("%d\n", count2);

    for(int i = 0; i<count1; i  ) {
        result[i] = text1[i];
    }

    for(int k = 0; k<count2; k  ) {
        result[k count1] = text2[k]; //k   1   count1 causes bug
    }

    result[count1 count2] = '\0' ; //adding NULL char at the end
    printf("%s\n" , result) ; //printing the string using %s

    return 0;
}

CodePudding user response:

Instead of defining the size of your result array as 100, you should define it equal to the sum of the length of both the input arrays.

Also, the format specifier should be %c

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

int main() {
    char text1[] = {"Hello"};
    char text2[] = {", how are you?"};
    int count1 = strlen(text1);
    int count2 = strlen(text2);
    char *result = malloc(count1   count2);
    printf("%d\n", count1);
    printf("%d\n", count2);
    
    for(int i = 0; i<count1; i  ) {
        result[i] = text1[i];
    }
    
    for (int i = 0; i < count2; i  ) {
        result[count1   i] = text2[i];
    }
    
    for (int i = 0; i < count1   count2; i  ) {
        printf("%c", result[i]);
    }
    
    return 0;
}
  • Related