Sunday, 2 February 2014

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)?

Answers:-
I hesitate to mention this (hopefully it won't get down-voted), but thought I'd mention it in case it is useful.
For dynamic arrays (malloc or C++ new) you need to store the size of the array as mentioned by others or perhaps build an array manager structure which handles add/remove/count/etc. Unfortunately C doesn't do this nearly as well as C++ since you basically have to build it for each different array type you are storing which is cumbersome if you have multiple types of arrays that you need to manage.
For static arrays, such as the one in your example, there is a common macro used to get the size but not recommended as it does not check if the parameter is really a static array. The macro is used in real code though, e.g. in the Linux kernel headers although it may be slightly different than the one below:
#if !defined(ARRAY_SIZE)
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
#endif

int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf
("%u\n", ARRAY_SIZE(days));
printf
("%u\n", sizeof(ptr));
return 0;
}
You can google for reasons to be wary of macros like this. Be careful.
If possible, the C++ stdlib such as vector which is much safer and easier to use.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More