Problems with assigning values from one vector to another, using malloc

Asked

Viewed 29 times

-1

I’m trying to make a program that reads a certain amount of values and inserts it into a vector that uses memory allocation. After that I created two more vectors (in the same way as the previous one) to insert even and odd numbers into them. The first part is working correctly, the values are being inserted in the vector, however, when I try to assign the even and odd values to their respective arrays the program does not work properly and ends up leaving the output confused. The entire code is below. Thanks for the help.

The image below shows the data input and output.

Note: I executed the code in Replit

Essa é a saída do programa

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

int main(void) {
    int *pares, *impares, qtdPares = 0, qtdImpares = 0;
    int *vetorPrincipal, tamanho = 5;
    int i;

    vetorPrincipal = (int *) malloc(tamanho*sizeof(int));

    //ler os valores do vetor
    for (i = 0; i < tamanho; i++) {
        printf("Valor %d: ", i+1);
        scanf("%d", &vetorPrincipal[i]);

        if (vetorPrincipal[i] % 2 == 0) {
            qtdPares++;
        } else {
            qtdImpares++;
        }
    }

    //alocando dinamicamente a memória para os pares e impares
    pares = (int *) malloc(qtdPares*sizeof(int));
    impares = (int *) malloc(qtdImpares*sizeof(int));

    //inserindo os valores pares e impares em seus vetores
    for (i = 0; i < qtdPares; i++) {
        if (vetorPrincipal[i] % 2 == 0) {
            pares[i] = vetorPrincipal[i];
        }
        else {
            impares[i] = vetorPrincipal[i];
        }
    } 

    //imprimir o vetor principal
    printf("\nVetor = [ ");
    for (i = 0; i < tamanho; i++) {
        printf("%d ", vetorPrincipal[i]);
    }
    printf("]");

    //imprimir pares e impares
    printf("\n\nNúmeros PARES = [ ");
    for (i = 0; i < qtdPares; i++) {
      printf("%d ", pares[i]);
    }
    printf("]");

    printf("\nNúmeros IMPARES = [ ");
    for (i = 0; i < qtdImpares; i++) {
      printf("%d ", impares[i]);
    }
    printf("]");

    return 0;
}

1 answer

1

Program error

The error of your program is in this part:

//inserindo os valores pares e impares em seus vetores
for (i = 0; i < qtdPares; i++) {
    if (vetorPrincipal[i] % 2 == 0) {
        pares[i] = vetorPrincipal[i];
    }
    else {
        impares[i] = vetorPrincipal[i];
    }
}

Here we have two mistakes, the first is to make i < qtdPares instead of i < tamanho, the second is to use the same i to access three different vectors.

Logical error in stop condition for

In his for you want to go through all the indices of your vetorPrincipal, if he has 3 positions then the for need to repeat 3 times, if you have 4 then the for need to repeat 4 times and so on. In your example you use the variable tamanho to store the size of the vector and it is the one you should use in your loop, in this way:

for (i = 0; i < tamanho; i++) { // Igual quando voce leu os valores para o vetor

Error while using it i to access three different vectors

After changing your stop condition for we will have the following code:

for (i = 0; i < tamanho; i++) {
    if (vetorPrincipal[i] % 2 == 0) {
        pares[i] = vetorPrincipal[i];
    }
    else {
        impares[i] = vetorPrincipal[i];
    }
}

whereas the vetorPrincipal has the following values:

1 2 3 4 5

Here the problem is using the same i for all vectors. The error is that you are putting the numbers ímpares and pares in the same position as vetorPrincipal and that’s a mistake.

Let’s consider i = 3.

If i == 3, then vectorPrincipal[3] == 4

Four is even so let’s put in pairs[i]

Rising i by its value (3), we have pairs[3]

And here we have the problem, the position pares[3] is not part of your array (Your array has size 2 as there are only two pairs). When you print pares the number four will not appear as it was placed in an unknown memory position.

Your program produces the following outputs:

pairs: 0 2

odd: 1 0 0

Note that number two is in position pares[1] (second position of the vector), because when the content vetorPrincipal era 2, the i era 1. Behold:

i == 0, 1 // Adds 1 in odd vector position 0

i == 1, 2 // Adds 2 at position 1 of even vector

i == 2, 3 // Adds 3 in odd vector position 2

i == 3, 4 // Adds 4 at position 3 of the even vector, this position is not part of the vector

i == 4, 5 // Adds 5 in odd vector position 4, this position is not part of the vector

Solution

To solve this problem you need to have a variable for each vetor, in this way:

// Voce pode declarar as variaveis dentro do for se quiser
// for (int i = 0, i_par = 0, i_impar = 0; i < tamanho; i++)
int i_par = 0;
int i_impar = 0;

for (i = 0; i < tamanho; i++) {
    if (vetorPrincipal[i] % 2 == 0) {
        pares[i_par] = vetorPrincipal[i];
        i_par++;
    }
    else {
        impares[i_impar] = vetorPrincipal[i];
        i_impar++;
    }
}

Note that now the values will be placed in the correct positions

See your code working here.

Browser other questions tagged

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