In coming from higher level languages, I’m trying to rebase myself by learning c. I’m trying to understand pointers and memory allocation (something I’ve never had to think about before).
Code I’m trying
#include <stdio.h>
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52 };
printf("\nShuffling...\n\n");
shuffle(array, sizeof(array)/sizeof(int));
int i;
for(i = 0; i < sizeof(array)/sizeof(int); i++)
{
printf("%d\n", array[i]);
}
}
int shuffle(int *shuffle_array, int length)
{
int i, j, newArray[length];
for(i = 0, j = length; i < length; j--, i++)
{
newArray[i] = shuffle_array[j];
}
shuffle_array = newArray;
}
First, this doesn’t work and I’m trying to figure out why the array isn’t reversed on printing.
Second, comparing the concept of in-place editing vs returning a new item within c using malloc() and free().
When your function exits then your locally defined array drops out of scope and hence no longer exists.
You ought to memcpy back over the shuffle_array …
Furthermore you are also starting your read off the end of shuffle_array. The last element in the array is “length -1”.
Edit: Reading off the end of the array won’t necessarily cause a problem. Its just that what you are doing is undefined behaviour.
The reason you see the same data come back out as you put in is because you don’t actually change the data at all.
TBH for reversing an array a much better algorithm is to start at both ends and swap the data over. You could do that as follows:
This way you totally avoid the need for a seperate array and that final copyback. You also save a load of stack memory. Score all round in my opinion.