Richard has already pointed out the bug in your program. There is nothing to add to that.
As you are new to programming you should try to pick up the right habits from the very beginning. Therefore, I want to point out a couple of things to you could do better in this small example and which will make things clearer for you and for the reader of your programs.
1. Naming
Why do you call the pointer to your array
old
? Always use names that tell something about what's stored in the variable, structure or array. In this case we don't know what exactly is being stored here, so why don't we call it
values
(note the use of the plural!). And your variable old_size is in fact to hold the current size of the array, so why don't we simply call it
size
.
Now to your function. The main purpose of the function is to calculate the squares of all values in the input array. So it should be called something like
CalcSquares
.
2. Be consistent in using loop indices
In your main you allocate the array and should set the size variable straight away. We know that the array has this size, so we store it immediately:
int size;
...
size = 5;
values = (int*) malloc (size * sizeof(int));
Don't abuse the
size
variable as loop index. Use a separate variable for that and refer to the give size of the array always and only by your size variable:
int i:
...
for (i = 0; i < size; ++)
{
...
}
If you form your loops all like this it will be very easy to pinpoint any mistakes.
3. Understand parameter passing
Probably the biggest flaw in you program is the
new_size
parameter to the function
old_double
. It is passed by value. But you later use it as if you would expect it to be passed by reference. "By value" means, the value you set inside old_double will never be passed back to the caller! If you would like the caller to know what the new size of the array is, use passing "by reference" or in plain old C that is passing a pointer:
int* CalcSquares (int* pValues, int size, int* pNewSize)
{
int i, newSize;
newSize = size * 2;
pValues = realloc (pValues, newSize * sizeof(int));
if (pValues == 0)
{
*pNewSize = 0;
return 0;
}
for (i = size; i < newSize; ++i)
pValues [i] = pValue[i-size] * pValue[i-size];
*pNewSize = newSize;
return pValues;
}
4. Avoid printing in your worker functions
You want your function to perform one specific task, in that case calculating the squares. Don't intermix those things with printing. If you want to use your function later in another context you probably would not like the printing inside the function, but do it somewhere outside by the calling code.
5. Don't make allocation of memory to complicated
I assume you are doing this exercise to learn about
realloc
and that is fine. But in "normal" code you would try to keep the allocation of memory and the interface of your function as simple as possible.