Sizeof array of floats dynamically created

Jul 11, 2011 at 1:15pm
I have a private var :
float * w3d_p3d_af;

And into a function I have
w3d_p3d_af = new float[33];
<<sizeof(w3d_p3d_af)<<"";
<<sizeof(&w3d_p3d_af)<<"";
<<sizeof(*w3d_p3d_af)<<"";

And I have :
4
4
4

I still have not eat (maybe I need sugar ?)
Joking apart, can anybody help me ?


Jul 11, 2011 at 1:19pm
You are giving sizeof() a pointer type variable, so it gives you the size of a pointer in the 2 first cases.
In the third case, you are giving it a float, and a float is generally 32 bits too.

Can't you keep the allocated size in a variable somewhere?
Last edited on Jul 11, 2011 at 1:21pm
Jul 11, 2011 at 1:24pm
sizeof(w3d_p3d_af)

That's the size of a pointer. Usually 4 bytes.

sizeof(&w3d_p3d_af)

That's the size of a pointer to a pointer, so it's another pointer, so 4 bytes again.

sizeof(*w3d_p3d_af)

That's the size of the first float in the array. 4 bytes again.

Try changing float to char and see what changes. That will help you understand.


Also, try this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
  
float w3d_p3d_af[33];
std::cout <<sizeof(w3d_p3d_af)<<" ";
std::cout<<sizeof(&w3d_p3d_af)<<" ";
std::cout<<sizeof(*w3d_p3d_af)<<" ";

return 0;

}


This code will give you the size of the whole array.

Last edited on Jul 11, 2011 at 1:25pm
Jul 11, 2011 at 3:37pm
But I want to my array was dynamic and with a private scope
It is incredible, learn c++ during 6 months and I'm stopped here....

Have I to know myself the size of the array ?
Last edited on Jul 11, 2011 at 3:46pm
Jul 11, 2011 at 3:43pm
That's why i was saying :
Can't you keep the allocated size in a variable somewhere?

You could also use a vector instead. size() would give you the number of elements
Jul 11, 2011 at 3:46pm
I need array because I want to pass it to OPENGL ...
Jul 11, 2011 at 3:54pm
If you dynamically allocate a C array, you must keep record of its size in a separate variable as bartoli said.

You can use a vector in OpenGL:

1
2
3
std::vector<int> myVector;
...
SomeCallThatRequiresACArray(&myVector[0], /*probably it needs the size too */ myVector.size());
Jul 11, 2011 at 4:02pm
webJose said it right.

Use the vector class. It automatically allocates and deallocates the memory it uses, so you don't need to manually do it yourself with new[] and delete[]. Also it keeps track of its own .size().

At its core it's just a dynamically allocated C array. That's why you can use &myVector[0] or &myVector.front() (which both return the address of the start of the dynamic array) and OpenGL will never see the difference.
Last edited on Jul 11, 2011 at 4:03pm
Jul 11, 2011 at 4:21pm
Thank you very much !!
Topic archived. No new replies allowed.