using the 'delete' operator on array of structures

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • suvarna271
    New Member
    • Feb 2013
    • 19

    using the 'delete' operator on array of structures

    Suppose I have the following structure

    struct b
    {
    char fullname[100];
    char title[100];
    bopname
    };

    and i declare a pointer to the struct as follows
    b* bp;

    and at runtime,

    bp = new b[5];

    In the end, is the statement delete[ ] bp enough to release
    the dynamically allocated memory. Or do i need to separately delete bp[0],bp[1]...

    Does delete[ ] bp indicate that the array[ ] pointed by bp has to be deleted?? [I am confused as to how this happens, since the pointer only points at the 1st struct address]
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You only allocated 1 block of memory, called new once so you only have 1 block of memory to delete, you can only call delete once.

    You should always call new and delete exactly the same number of times over the course of a program running.

    The memory manager only needs the pointer to actually delete the block of memory, however the compiler needs to know that you are deleting an array of structures (or classes) so that it can call the destructor on every class in the array which can be demonstrated by adding constructors and destructors with cout statements

    Code:
    #include<iostream>
     
    struct b
    {
    	char fullname[100]; 
    	char title[100]; 
    
    	b() :
    	 number(++nextNumber)
    	{
    		std::cout << "Constructing b: " << number << std::endl;
    	}
    
    	~b()
    	{
    		std::cout << "Desstructing b: " << number << std::endl;
    	}
    	
    private:
    	int number;
    	static int nextNumber;
    };
    
    int b::nextNumber = 0;
     
    int main()
    {
    	b* bp;
    
    	bp = new b[5];
    
    	delete[] bp;
    }
    This demonstrates destructing every structure constructed, if you changed line 32 to remove the [] you will fiuns that although the block of memory is deleted only the destructor for the first element of the array is called.

    Comment

    • suvarna271
      New Member
      • Feb 2013
      • 19

      #3
      Thanks Banfa :) That cleared my doubts.

      Comment

      Working...