-1

If I have declared a double *positions[2] array, is there a way of finding the actual size of the double *positions[2] array?

Is there like a sizeof function to find the size?

I have tried an example, and it does not return the size as 4

http://ideone.com/vp3tJz

Stu User
  • 77
  • 2
  • 3
  • 8
  • http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array – Amol Bavannavar Dec 05 '14 at 11:33
  • You don't need any code for this. The length of the array is `2`. That's known at compile time. – David Heffernan Dec 05 '14 at 12:06
  • No I meant the number of elements stored inside the pointer array – Stu User Dec 05 '14 at 12:08
  • Why didn't you ask that then? The answer is that you cannot find how many elements are in a dynamically allocated array if all you have is a pointer to the array. My question to you is why you feel compelled to call `new[]` at all. You can avoid all these problems by using standard containers. – David Heffernan Dec 05 '14 at 12:10
  • Actually looking at your code, I wonder what you expect `coord[2]` and `coord[3]` to mean. You declared `coord` like this `double *cord[2]`. Do you understand what the `2` means in that statement. In other words, if you want to use 4 elements, why did you reserve 2? – David Heffernan Dec 05 '14 at 12:12

1 Answers1

1

Why not to use sizeof? Expression

sizeof( positions )

will return the size of the array in bytes that is equal do 2 * sizeof( double * ) Or you can use standard class std::extent to determine the num ber of elements in an array. For example

std::cout << std::extent<decltype( positions )>::value << std::endl;

As for your edited post then the declaration of the array does not correspond to the values you showed. The array is defined as having pointers as its elements not double values.

If you want to define an array that will be initialized with values

0.1, 2.5
10.0, 56.7
12.4, 20.1
69.9, 69.9
72.1, 45.0

then you should write

double positions[5][2] =
{
    { 0.1, 2.5 },
    { 10.0, 56.7 },
    { 12.4, 20.1 },
    { 69.9, 69.9 },
    { 72.1, 45.0 }
};

In this case sizeof( positions ) will be equal to 5 * 2 * sizeof( double )

Or

sizeof( position ) / sizeof( *positions )

will be equal to 5 and

sizeof( *position ) / sizeof( **positions )

will be equal to 2

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335