Joining of vectors in C

Asked

Viewed 105 times

0

I have a doubt in this code because the function should print {1,2,3} but I printed {1,2,3,4,10,24,73}

void uniao(int A[], int B[], int C[]){
int i;

for(i = 0; i < TAMANHO ; i++){
    if (A[i] == 1){
        C[i] = A[i];    
    }
    if (B[i] == 1){
        C[i] = B[i];    
    }
}

}

The print function I used was:

void imprimir( int vet[], int tam) {
int i;

for (i = 0 ; i < tam ; i++){
    if( vet[i] == 1){
        printf("Conjuntos: %d \n",i );  
    }

}

}

main of Cod:

int A[TAMANHO] = {0,0,1,1};
int B[TAMANHO] = {0,1,1,1};
int C[TAMANHO];


uniao(A,B,C);
imprimir(C,TAMANHO);
  • Here: http://ideone.com/NwHEA4 worked correctly.

  • Hey, it really works by adding size like 4, but I need to add size like 200. And when I do that it keeps printing the numbers 10,24 and 73.

  • But when you report size 200 you report the 200 values of each of the vectors?

  • no, this size is just what is asked in the statement of the question (which I did not understand very well, so I am full of doubts). In this case the functions have to be very generic as they will be tested in other programs.

  • In this case it is better to put the size of the vectors as parameter also in the union function.

  • Now an observation: from what I understand of union its function does not make the union of vectors.

  • I think it’s all very confusing, especially in my understanding of this work (some functions I’m using the already provided by the teacher). But thanks for trying to help me ;)

  • When you change the size to 200, how do you initialize the A and B vectors?.

Show 3 more comments

1 answer

0


The problem is that the vector C is not being initialized. This means that the way it is implemented it is getting "random" values from memory and to solve this you need to first boot it.

There are several ways to initialize an array, but for this example I will show the most explicit, with a loop:

int C[TAMANHO];

for (int i = 0; i < TAMANHO; i++) {
    C[i] = 0;
}

This way the result will always be determined and your example will be executed as expected.

  • Thank you for helping me, but I managed to solve the problems of this code, thank you :)

Browser other questions tagged

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