Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the 'sizeof' (a pointer pointing to an array)?

First off, here is some code:

int main()  {     int days[] = {1,2,3,4,5};     int *ptr = days;     printf("%u\n", sizeof(days));     printf("%u\n", sizeof(ptr));      return 0; } 

Is there a way to find out the size of the array that ptr is pointing to (instead of just giving its size, which is four bytes on a 32-bit system)?

like image 832
jkidv Avatar asked Jan 29 '09 16:01

jkidv


People also ask

Can a pointer point to an array?

C. In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.

Can you call sizeof on a pointer?

The code calls sizeof() on a malloced pointer type, which always returns the wordsize/8. This can produce an unexpected result if the programmer intended to determine how much memory has been allocated. The use of sizeof() on a pointer can sometimes generate useful information.

How do I get the size of a pointer in C++?

If we have some object type T, and we have a pointer T* ptr which points to an object of type T, sizeof(ptr) would give us the size of the pointer and sizeof(*ptr) would give us the size of the object ie. sizeof(T). If the object type T is an array, then sizeof(*ptr) would give us the size of the array.


2 Answers

No, you can't. The compiler doesn't know what the pointer is pointing to. There are tricks, like ending the array with a known out-of-band value and then counting the size up until that value, but that's not using sizeof().

Another trick is the one mentioned by Zan, which is to stash the size somewhere. For example, if you're dynamically allocating the array, allocate a block one int bigger than the one you need, stash the size in the first int, and return ptr+1 as the pointer to the array. When you need the size, decrement the pointer and peek at the stashed value. Just remember to free the whole block starting from the beginning, and not just the array.

like image 194
Paul Tomblin Avatar answered Oct 21 '22 07:10

Paul Tomblin


The answer is, "No."

What C programmers do is store the size of the array somewhere. It can be part of a structure, or the programmer can cheat a bit and malloc() more memory than requested in order to store a length value before the start of the array.

like image 33
Zan Lynx Avatar answered Oct 21 '22 06:10

Zan Lynx