0

I have the below code:

int* d = (int*) malloc(100 * sizeof(int));
cout<<"size of d which is pointer is: " << sizeof(d)<<endl;

I know that sizeof outputs 4 as d is a ptr. But, how can I find the sizeof the entire array using sizeof

Programmer
  • 6,565
  • 25
  • 78
  • 125

4 Answers4

7

You cannot - sizeof is a compile time operation and hence not dynamic.

As you are using c++ use std::vector instead. Otherwise create a structure to store both the pointer and the size of the array. Pass that around instead.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

The pointer gives you the place in memory where your data is stored which is why you can't get it's size only from that information.

It's analogous to knowing how big my house is from knowing my address (without prior knowledge or the use of tools like Google Maps)

Yuuta
  • 414
  • 2
  • 13
1

The direct ans. is no you can't but you can try this :

int x[]={1,2,3,4};
int *ptr=x;
decltype(sizeof(*ptr)) size=0;
while(*ptr<5){
          size =size+sizeof(*ptr);
          ptr++;
          }
          cout<<"Size is : "<<size;

Output:

Size is:16

Arpit
  • 12,767
  • 3
  • 27
  • 40
1

You could argue that you already know the size of the entire array using sizeof - you've got it in your original malloc call - 100 * sizeof(int). Although the malloc machinery must know the amount of memory associated with the pointer internally (it needs it for a corresponding free call), and apparently some implementations provide functions to return this information, as far as I know there is not implementation-independent and portable way of doing this without handling it yourself.

Michael
  • 1,136
  • 1
  • 7
  • 15