tags:

views:

357

answers:

5

Hi, a friend of mine declared a new type using

typedef GLfloat vec3_t[3];

and later used vec3_t to allocate memory

vertices=new vec3_t[num_xyz* num_frames];

He freed the memory using

delete [] vertices;

Question:
1. Since vec3_t is an alias for GLfloat[3], does it mean that

vec3_t[num_xyz* num_frames] 

is equivalent to

GLfloat[3][num_xyz* num_frames];  

2. If the above is a 2 dimentional array, How is it supporsed to be properly deleted from memory?

thanks in advance;
from deo

+2  A: 

It will be deleted the same way it's been allocated - one contiguous piece of memory.

See 2D array memory layout

djna
this not entirely correct there is a difference between allocation an array and allocating a single object. that's why you have delete vs delete[]
Eli
The visualization in the first example of your link is misleading - ttt is defined as an array, not as a pointer.
hjhill
+1  A: 

I think that the delete is OK, but to reduce confusion I tend to do this:

struct vec3_t{
  GLFloat elems[3];
};

vec3_t* vertices = new vec3_t[num_xyz* num_frames];

Now you can see the type of vertices and:

delete [] vertices;

is obviously correct.

quamrana
+2  A: 

You almost got it right,

vec3_t[num_xyz* num_frames]

is equivalent to

GLfloat[num_xyz* num_frames][3]

Since you allocated with new[], you have to delete with delete[].

avakar
+2  A: 

GLfloat is an array that is "statically" allocated and thus that doesn't need to be explicitly deallocated.

From a memory point of view, this typedef is equivalent to the following structure:

typedef struct {
  GLfloat f1;
  GLfloat f2;
  GLfloat f3;
} vec3_t;

You can then have the following code which is now less confusing:

vec3_t* vertices = new vec3_t [num_xyz* num_frames];
[...]
delete[] vertices;
cedrou
+7  A: 

1. a two dimensional array can be thoght of as a one dimensional array where each element is an array.
using this definition you can see that new vec3_t[num_xyz* num_frames] is equivalent to a two dimensional array.

2. this array is made of num_xyz* num_frames members each taking a space of sizeof (vec3_t)
when new is carried out it allocates num_xyz* num_frames memory blokes in the heap, it takes note of this number so that when calling delete[] it will know how many blocks of sizeof (vec3_t) it should mark as free in the heap.

Alon