-1

If I build a function with a introduced pointer like this:

int* c=new int[16];

And return it

return c;

How can I determine the size of c, (16), in my main(). I can't use sizeof because c isn't an array...

Élio Pereira
  • 181
  • 1
  • 14
  • 1
    http://stackoverflow.com/a/37539/212869 – NickSlash Dec 21 '14 at 22:51
  • @NickSlash THX for finding the dupe. That well explains about the problem! – πάντα ῥεῖ Dec 21 '14 at 22:52
  • possible duplicate of [How do I determine the size of my array in C?](http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c) – πάντα ῥεῖ Dec 21 '14 at 22:52
  • This is different question. The above SO links answer how to find the number of elements of array. And the question is - how to find the allocated object/array size by its pointer. I think the necessary value can be found by reading near bytes (pointer minus 2/4, etc.) which depends on malloc implementation. – i486 Dec 21 '14 at 23:13

2 Answers2

4

Since c is a pointer to int (that's what int* c means), what you get from sizeof(c) is exactly the size of the pointer to int. That is why sizeof(c)/sizeof(int*) gives you 1.

If you define c as array, not the pointer:

int c[16];

you'll get its size.

striving_coder
  • 798
  • 1
  • 5
  • 7
1

You can't get number of elements in dynamically allocated array. It would work in this case:

int c[16];
int num_elements=sizeof(c)/sizeof(int);

In your case sizeof(c) is probably 4 (size of pointer).

Andrey
  • 59,039
  • 12
  • 119
  • 163