I want to be able to vary the size of my array so I create one this way:
int* array;
array = malloc(sizeof(int)*10);//10 integer elements
I can use this like an array as you normally would, however when I try to find the size of it like so:
size = sizeof(array)/sizeof(int);
I get the answer 1 because its not recognizing it as pointing to an array
How can I get the size of the array ? (I know its not technically an array but is there a way to work out the whole size of the allocated memory block ?)
Also am I right in assuming what I have stated in the description ? If I am technically wrong about something please correct me.
int size = rowSize * colSize; int newSize = size + rowSize; int *randomNum; randomNum = malloc(size * sizeof *randomNum); randomNum = realloc(randomNum, newSize * sizeof *randomNum);
malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available.
There are lots of ways in which malloc/free can store the size of the memory area. For example, it might be stored just before the area returned by malloc. Or it might be stored in a lookup table elsewhere. Or it might be stored implicitly: some areas might be reserved for specific sizes of allocations.
The pointer is a pointer, and not an array. It can never be "recognized as an array", because it is not an array.
It is entirely up to you to remember the size of the array.
For example:
struct i_must_remember_the_size
{
size_t len;
int * arr;
};
struct i_must_remember_the_size a = { 10, NULL };
a.arr = malloc(a.len * sizeof *a.arr);
There's no standard way to do what you ask. Some compilers may provide a function for that, or some other allocators may have such a function, but, as already said there's nothing standard.
Notice that the sizeof
applied over arrays does not work because it recognizes the pointer "as from an array": it just recognizes its argument as an array (sizeof
is one of the few contexts in which an array do not decay to a pointer to its first element); once your array decays to a pointer sizeof
will only yield the size of the pointer.
First of all, sizeof() returns the size of a "type"; it doesn't know a thing about allocated memory.
Second, there is no way to get the size of a malloc()ed block, UNLESS you want to dig into the internals of the runtime library of your compiler. Which is most definitely not a good idea, especially since it's no problem to remember the size elsewhere --- you could prefix the memory block with another item to store the size, or you could store it separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With