Hello, I'm struggling to use calloc and realloc for my array initializations. I'm trying to write a program which calculates a final sum from the command line arguments using fork() with a companion program.
If I receive a odd set of integers from the command line such as: ./program 1 2 3 4 5.
It should see that amount is odd and initialize my input array to 6 spots and put a zero in the very last spot. Such as this: [0] = 1, [1] = 2, [2] = 3, [3] = 4, [4] = 5, [5] = 0. So that my companion program is able to do the computation.
If I receive a even of amount of integers from the command line such as: ./program 1 2 3 4. It would do the same as above, except without the zero because the set of integers is even.
The output array should be initialized to whatever the amount of integers is divided by 2. So if I had 6 arguments, it would be initialized to 3. If I receive an odd amount of integers such as 7, it would reallocate input array and put the zero at the end, thus making the amount of integers 8. So it would divide that by 2 and make the output initialize to 4.
My output array would eventually hold the sums of each pair of numbers. So the above would be.
1+2=3, 3+4=7, 5+0=5.
Then it the output array would hold [3],[7],[5]. Then the loop would continue from that and calculate the final sum from the remaining arguments.
I can't get that point though because my arrays aren't initializing correctly and adding the zero to the input array if the # of arguments is odd.
Refer to the code below:
#include <stdio.h> /* printf, stderr, fprintf */
#include <unistd.h> /* _exit, fork */
#include <stdlib.h> /* exit */
#include <errno.h> /* errno */
#include <sys/wait.h>
int main(int argc, char** argv)
{
int size = argc - 1;
int* input;
int* output;
int calc;
if(size == 1 && size % 2 != 0)
size++;
if(size % 2 != 0)
{
calc = (size+1)/2;
input = (int*)realloc(NULL,(argc));
output = (int*)calloc(calc, sizeof(int));
int j;
for(j = 1; j < argc; j++)
{
input[j-1] = atoi(argv[j]);
}
input[argc] = 0;
}
else
{
calc = (size)/2;
input = (int*)realloc(NULL,(size));
output = (int*)calloc(calc, sizeof(int));
int j;
for(j = 1; j < argc; j++)
{
input[j-1] = atoi(argv[j]);
}
}
int i;
for(i = 0; i < argc; i++)
printf("input[%d]: %d\n",i,input[i]);
free(input);
free(output);
exit(0)
}