user3334513
user3334513

Reputation: 1

create a dynamic array of object, delete object and free memory in C++

Hello everybody ! I am a beginner in C++ so I don't really have a good experience.

I want some help,

I try to create a dynamic array of object (type ELEMENT), I have a problem when I want to delete an object from array (Error 2157)

This is a part of code :

class ELEMENT
{
private :
     int id_num;
     int nbnr;
     int BI;
public :
: void () ................
: ...............
:  
 };

 ELEMENT *T;   

/* before calling the next fonction, I allocate a dynamic memory space every time for T by
 T = new TAB;  because I don't know the exact size of T, I don't know if it's right like this ?
*/

void eval (int nr, int BS)
{

for (int i=0; i< size; i++)
{if (T [i].BI >= BS)
delete T [i];   // I try to delete the object in position (i) and also free allocated memory
// before I tried with delete [] T; doesn't work !
}

}

and the other question, is there any function to get the current size of T. I tried with SizeOf(T) doesn't give right value.

That's all, thanks for your answers !

Upvotes: 0

Views: 289

Answers (3)

Marko Popovic
Marko Popovic

Reputation: 4153

With statement ELEMENT *T you have created a pointer to an object of class ELEMENT, but that pointer is not currently initialized ( it is not pointing to any object ). Use

ELEMENT *T = new ELEMENT;

to initialize the pointer to an object.

For the size of an array you can use

sizeof(nameOfYourArray)/sizeof(nameOfYourArray[0])

which calculates the size of an array by dividing total number of bytes with the number of bytes occupied by the first element.

Hope this helps!

Upvotes: -1

songyuanyao
songyuanyao

Reputation: 172924

Firstly, you can't delete one element from an array and free the memory. You can only delete the while array by delete[].

Secondly, you define T as a pointer of ELEMENT, so sizeof() will return the pointer size but not the array's size. You can remember the size by yourself, or define T as an array such as ELEMENT T[10].

Upvotes: 0

mathematician1975
mathematician1975

Reputation: 21351

You need to decide on the size of your array and then allocate dynamically as

T = new ELEMENT[size];

This creates an array of ELEMENT items which you delete once with

delete [] T;

You should not call delete on each element of T. The only time you would need this would be if T contained pointers to dynamically allocated memory (which they do not in your case) so do not do this.

There is no way to get the size of T using a dynamically allocated array. However, if you were to use std::vector instead you would be able to do this and also not have to worry about memory allocation and release at all.

Upvotes: 2

Related Questions