Since this is homework, I will make some general comments, and I hope this helps not only solve your problem, but also improve your programming style.
The code contains:
if(size == 1 && size % 2 != 0) size++;
If size is 1, then size % 2 will also be 1, so your second check is always true. The effect of the two lines looks as if you wrote:
if (size == 1) size = 2;
I doubt that this is what you want.
Given the problem operator, your input variable will store the elements n or n+1 , where n is the number of numbers you want to add and is equal to argc-1 .
In C, integer division truncates, so 1/2 is 0 , 5/2 is 2 , etc. Mathematically, 5/2 , of course, 2.5. In the statements below, I distinguish between "C" and the true mathematical mapping, writing // for the latter.
Now for your output array you need elements n//2 if n is equal, and (n+1)//2 if n is odd. Due to the property of integer division mentioned above, you can make sure that your output array will always contain (n+1)/2 elements.
If you do not need to spend one element on a space, you can always select n+1 elements for your input, and then set n+1 th element to zero, before you start reading numbers from the command line, linear arguments. This has the following advantages:
- No need to worry about even or odd numbers in the rest of your program,
- You do not need
calloc() : you just set the last element to zero. The rest of the elements will be written, and the last element that you set to zero will be overwritten if you even have the number of elements.
Now about your call to realloc() :
input = (int*)realloc(NULL,(argc));
This has the following "problems":
realloc(NULL, size) equivalent to malloc(size) , so you should replace realloc() with malloc() .- You do not need to specify the return value from
malloc() , calloc() and realloc() . In fact, casting can hide errors from refusing to include stdlib.h . - You need
argc times sizeof(int) bytes, not argc . These two will be equal only if sizeof(int) is 1. - Given the pointer
T *p; , itβs easier for me to write malloc() calls as p = malloc(n * sizeof *p); - it's easier to write, easier to read and independent of type p .
So, making the above changes, you will receive:
size_t n = argc - 1; input = malloc((n+1) * sizeof *input);
atoi() does not check errors: if you find out about strtol() , you should use this.
When you add numbers together, you can:
count := 0 while count < n: output[count/2] := input[count] + input[count+1] count := count + 2