How to create a vector by joining together 2

Asked

Viewed 1,267 times

1

I’m doing an exercise with vectors where I need to read two vectors of 5 positions each, and after that, concatenate these two into a 3 of 10 positions.

My program is correctly printing the first vector, but in the second it prints 4, 5, 5, 2686760, 1987092020 (I think they are addresses).

Carry out the duties:

int criaVetor3(int v[], int v1[]){

int v3[10];

for(i=0; i<=4; i++){
    v3[i] = v[i];
}

for(i=4; i<=9; i++){ // Começa no 5 elemento do vetor e vai até o 10
    v3[i] = v1[i-5];
}
}

int mostraVetor3(int v[], int v1[]){

int v3[10];

for(i=0; i<=9; i++){
    printf("O numero posicao [%d] e %d\n", i, v[i]);
}

}

2 answers

1


This code doesn’t even compile. Solving these problems went all right, I just stylized better.

Missing variable declaration and missing to return or pass a coverage vector, which I preferred to do to not involve dynamic allocation.

#include <stdio.h>

void criaVetor(int v[], int v1[], int v2[]) {
    for (int i = 0; i < 5; i++) v[i] = v1[i];
    for (int i = 0; i < 5; i++) v[i + 5] = v2[i];
}

void mostraVetor(int v[]) {
    for (int i = 0; i < 10; i++) printf("O numero posicao [%d] e %d\n", i, v[i]);
}

int main(void) {
    int v[10];
    int v1[] = {1, 2, 3, 4, 5};
    int v2[] = {6, 7, 8, 9, 10};
    criaVetor(v, v1, v2);
    mostraVetor(v);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much, I did not put the whole code because it has some more functions and a menu, I put only the functions of the part I was having difficulty but anyway, I really appreciate the help!

-2

Good,

The mistake happened to me too and I found out.

Example: Vector 1 = 1, 2, 3 and Vector 2 = 9, 8, 7

Vector 3 joins the first and the second.

See, when you put the first go, the index of vector 3 and vector 1 are equal and put the information correctly.

But when you try to put the second vector, vector 3 gives this error.

 Vetor 1 = 1, 2, 3 

Position of i = 0, 1, 2

 Vetor 2 = 9, 8, 7 

Position of i = 0, 1, 2

 Vetor 3 = 1, 2, 3, 9, 8, 7

Position of i = 0, 1, 2, 3, 4, 5

For i=0; for as long as it is less than 3; i++;

V3[i] = V1[i];

For the next reasoning, let’s use an auxiliary variable, because the position of vector 2 has to be traversed from the beginning at 0 and not equal to i starting at 3.

aux=0;

For i=3; as long as it is less than 6; i++, aux++;

V3[i] = V2[aux];

So will.

Try to understand and see if it works. It worked for me...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.