-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
#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;
}