I have to do the following:
Given a vector with random numbers, separate it in 2 other vectors, odd and even. But in the function, all vectors must be passed via parameter (can’t use global).
Here is my code:
#include <stdio.h>
#include <stdlib.h>
void vetores(int *vetor, int *A, int *B)
{
int i = 0,aux;
for(i = 0;i < 100; i++)
{
if(vetor[i] % 2 == 0)
{
aux = vetor[i];
A[i] = aux;
}else{
aux = vetor[i];
B[i] = aux;
}
}
}
int main()
{
int vetor[101], a[51], b[51],i;
/*a = (int)malloc(sizeof(int)*51);
b = (int)malloc(sizeof(int)*51);*/
for(i = 0; i < 100; i++)
{
vetor[i] = i;
}
vetores(vetor,a,b);
for(i = 0; i < 50; i++)
{
if(vetor[i] % 2 == 0)
{
printf("%d",a[i]);
}else
{
printf("%d",b[i]);
}
}
return 0;
}
If you test that code, the vector is being altered (it is not supposed to) and the A vector is not receiving the even numbers!
Your main problem is that you’re indexing your outputs based on the position in the input.
For example, if your first even number is at
input[3], then you’re writing it toeven_output[3], where is should (probably) be ateven_output[0].You probably want something like:
You probably also need to do something to tell the caller how many odd and even numbers you found (and the caller may have to allocate memory a bit differently unless those counts are equal — right now, you have 101 inputs, and 51 spots allocated for each output. If you had (for example) 60 even and 40 odd numbers, you’ll write beyond end of the space you’ve allocated for the even numbers. With the inputs you’ve provided, that problem won’t arise, but in almsot any other case, it’s not only possible, but in fact likely.