In my Computer Science course, we have been taught a method of storing a value in the 0th element of a malloced array, then incrementing the array so that things such as the size of the array can be stored in that element and retrieved later. I have tried using a modified version of this method to store various datatypes in these incremented elements.
Here is an example of how such an array is created:
int *array;
array = malloc(sizeof(int) + sizeof(double) + (n * sizeof(int)))
*(array) = n;
array++;
(double*)array++;
return array;
In this example, the sizeof(int)
and sizeof(double)
in the malloc statement are the elements that will store things, such as the size of the array in the int element, and in the double element we can store something like the average of all the numbers in the array (excluding these two elements of course)
(n * sizeof(int))
is for creating the rest of the elements in the array, where n
is the number of elements, and sizeof(int)
is the desired data type for these elements, and in theory this should work for an array of any data type.
Now, here is the trouble I am having:
I have created another function to retrieve the size of the array, but I am having trouble decrementing and incrementing the array. Here is my code:
getArraySize(void* array){
(double*)array--;//Decrement past the double element
(int*)array--;//Decrement past the int element
int size = *((int*)array);//Acquire size of the array
(int*)array++;//Increment past int element
(double*)array++;//Increment past the double element
return size;}
This function fails to get the size of the array, and I have realized it is because the compiler first increments the array then type casts it. However, when i try to fix such increment/decrement statements as follows:
((int*)array)++;
I get an error that says lvalue required as increment operand
. I do not know how to fix this notation in such a way that it will increment and decrement correctly. Any suggestions would be much appreciated.