Union of two vectors in C

1

I need to merge two vectors, resulting in a third vector:

a[5]={1, 2, 3, 4, 5}, b[5]={6, 7, 8, 9, 10}, c[10];
else if (select_menu == 4) {
    int select_f4, i, j, x;
    printf("Esta é uma opção que realiza a união dos conjuntos\n");
    printf("Resultado da união entre os dois vetores, com os números inseridos até o momento: \n");
    for(i=0; i<5; i++){
        c[i] = a[i];
    }
    for (j=0; j<5; j++){
        c[i] = b[j];
    }
    for (x=0; x<10; x++){
        printf("%d, ", c[x]);
    }
}

The result should be:

  

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Instead, it gets:

  

1, 2, 3, 4, 5, 10, 257, 0, 1152, 0

    
asked by anonymous 03.07.2018 / 06:40

3 answers

3

Just swap c[i] = b[j]; with c[j + 5] = b[j]; .

After all, the first 5 items are for a and the last 5 for b . Without this + 5 , you would put b over a . However, since you were accessing c with variable i and b with j , you were putting all elements of b (worth the last, which is 10) in c[5] .

These numbers 257, 0, 1152 and 0 are probably garbage .

One way to avoid errors like this is to declare variables only in the smallest required scopes, which in your case is only in for itself. For example:

        for (int i = 0; i < 5; i++) {
            c[i] = a[i];
        }
        for (int j = 0; j < 5; j++) {
            c[i] = b[j]; // O compilador vai mostrar que aqui há um erro!
            c[j + 5] = b[j]; // Isso seria o correto.
        }
        for (int x = 0; x < 10; x++) {
            printf("%d, ", c[x]);
        }
    
03.07.2018 / 06:48
4

No for loop is needed to solve your problem!

You can use the memcpy() function of the standard library string.h to join the two vectors into a third vector, see:

int a[5] = { 1, 2, 3, 4, 5 };
int b[5] = { 6, 7, 8, 9, 10 };
int c[10];

/* Copia vetor 'a' para a primeira metade do vetor 'c' */
memcpy( c, a, sizeof(a) );

/* Copia vetor 'b' para a segunda metade do vetor 'c' */
memcpy( c + 5, b, sizeof(b) );

See working at Ideone.com

Alternatively, you can make this union independent of the size of the input vectors, as long as the output vector has the sum of the sizes of the input vectors:

int a[7] = { 1, 2, 3, 4, 5, 6, 7 };
int b[3] = { 8, 9, 10 };
int c[10];

/* Copia vetor 'a' para a primeira porção do vetor 'c' */
memcpy( c, a, sizeof(a) );

/* Copia vetor 'b' para a segunda porção do vetor 'c' */
memcpy( c + (sizeof(a)/sizeof(int)), b, sizeof(b) );

See working at Ideone.com

    
03.07.2018 / 13:04
0

Simple, in the second for you are not adding the variable i , to be clearer to your way of understanding:

for(i=0; i<5; i++){
    c[i] = a[i];
}
for (j=0; j<5; j++){
    c[i] = b[j];
    i++;//desta forma você atualiza a posição em que será inserido no vetor c
}
for (x=0; x<10; x++){
    printf("%d, ", c[x]);
}

the values being viewed differently were garbage of the positions in the vector c

    
03.07.2018 / 13:33