You have three problems here. The first is trivial, you're returning the first element of the array with return *array
, when what you mean is to return a pointer to the first element of the array with return array
. DON'T STOP HERE! The second is that you are incrementing your pointer by 1, rather than by the size of the data you're pointing to. This will cause you to get wrong results. The third problem is much more serious:
You allocate memory for your array on this line:
void* array[array_size];
This memory is allocated on the stack, and this memory is no longer allocated when you return from the function. When you later reference this memory with the line:
int* a = (int*)list_to_array(list);
a is pointing to a region on the stack which is no longer in use. You get somewhat reasonable results with the code you have, but if you modify the stack after returning from your function, a will be pointing at the new memory. For example, if you use the following code:
int* a = (int*)list_to_array(list1);
int* b = (int*)list_to_array(list2);
printf("%d" (int)a);
You will (likely) see the first element of b. This is not guaranteed - You may also get a segmentation fault. Other code between the assignment to a
and its use will also overwrite the contents of the memory you access in your printf statement.
You need to allocate your memory with the same scope as a.
// Prototype
void* list_to_array(SList* list, void* dest_array);
// C99 (Or use malloc)
void* array[list_get_length(list)];
int* a = (int*)list_to_array(list, array);
other_functions();
// Works every time!
printf("%d" (int)a);
The less serious problem is the fact that you're not incrementing your pointer by the correct amount. You need to use the sizeof() operator. Alternatively, you can access your array elements with [].
int* a = (int*)list_to_array(list, array);
printf("%d" a[1]); //Prints second element of a
a += sizeof(int) * 2;
printf("%d" (int)a); //Prints third element of a