How to use new

This is a discussion on How to use new within the C++ Programming forums, part of the General Programming Boards category; Hi all, I am new to c++. I know how to create a new int array int *p = new ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    How to use new

    Hi all,


    I am new to c++.
    I know how to create a new int array
    int *p = new arr[5];

    But how do I create an array of pointers ?
    (
    In c I would go :
    int **pp = malloc(5*sizeof(int*));
    )


    More that that, is it customery in c++ to use stdlib functions of c ?
    I failed to use cout >> etc....
    So I use printf instead.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    I know how to create a new int array
    int *p = new arr[5];
    apparently not.
    Code:
    int *p = new int[5];
    to create an array of pointers is similar to above
    Code:
    int** p = new int*[8];

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    Thank you

    int **pp = new int*[8];

    Do I release memory by
    delete *[]pp;
    ?

    Thanks again.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    You have a pointer to an array of pointers. Assuming you initialized the pointers to something you would first delete them then delete the pointer to the array.
    Code:
    for (int i=0;i<8;++)
    delete pp[i];
    
    delete [] pp;/

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    Thanks

    I know this code dont make sense.
    But is this right ?

    int *pint = new int;
    int *po = new int[5];
    int **pparr = new int*[5];


    delete pint;
    delete []po;
    delete *[]pparr; // or delete []pparr ? */


    And more than just syntax :
    How come u have to tell delete something about the address u are releasing ?
    In c u just free(pint) free(po) free(pparr).
    free() dont care at all about the type.

  6. #6
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    delete[] pparr;

    any time you use new[] then you use delete[], regardless of the number of stars.

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    You mean why delete[] and delete?

    It's got, among other things, something to do with destructors. Only with [] does delete know to call more than one destructor. (Which doesn't give you permission to mix them if the underlying object doesn't have a destructor.)
    In C, there's no such thing as destructors. malloc just gives you a block of memory, free frees it; neither cares about what that memory contains. new and delete do more, which is why they need to know more.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    Thank u all very much

    Thanks all,

    Thanks CornedBee, thats what I meant.
    May I ask for u to elabrote on :

    "Only with [] does delete know to call more than one destructor."

    How come u get more than one destructor ?

    Thanks in advance.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Because there's more than one object. Suppose you do this:
    Code:
    string *p = new string[3];
    Then you've got three strings. So you need to call the destructor for each one.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    Thanks again

    Thanks CornedBee,

    But i am unfillimar with the class string.

    I think I have to do some reading.

  11. #11
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    std::string (in MSDN, look for basic_string) is the string class of the standard library. But it might be anything, that's irrelevant to my point.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  12. #12
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    Thanks again

    Thanks CornedBee,


    But I failed to understand from this article anything.

    One more qustion, I have.
    When does the desrctor is called when copying objects ?
    is it at end of the program or end of the function ?
    I worte this program as an example.


    Code:
    struct base
        {
         int    *p;
         base(int  Ix)
              {
               p = new int;
               *p = Ix;
               }
         ~base(void)
               {
               delete p;
               }
           };
           
    void fun(base  b1)
    {
    printf("%d\n", *b1.p);
    }
    
    void main(void)
    {
    base irelvanet(9);
    
    fun(irelvanet);
    }

    when will the desructor function base::~base will be called for b1 ?
    Is it at end the function fun(base b1) ?
    Or the end of main() ?

  13. #13
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    Seem to understand part of it

    This is an example to illsratete it :




    Code:
    #include <iostream>
    #include <mylib.h>
    
    #define  N   3
    
    class mstr 
      {
      char   *str;
    public :
      mstr(void)
         {
         str = NULL;
         }
       void add_new(const char *s)
         {
         str = new char[strlen(s)+1];
         strcpy(str, s);
         }
        ~mstr(void)
        {
        if ( str )
          {
           printf("delete %s\n", str);
           delete str;
           }
        }
        void show(void)
        {
        printf("%s\n", str);
        }
    };
    
    
    class strt
    {
       public :
       mstr  *tbl;
       strt(void)
         {
         tbl = new mstr[N];
         tbl[0].add_new("strt :one");
         tbl[1].add_new("strt :two");
         tbl[2].add_new("strt :three");
         }
       void disp_tbl(void)
         {
         for ( int i = 0 ; i < N ; ++i )       
             tbl[i].show();
         }
    };
    
    
    
    int   main(void)
    {
    strt  st1, st2;
    int   *p = new int[5];
    
    delete p;
    
    st1.disp_tbl();
    
    printf("===> delete []st1.tbl <=== : \n");
    delete  []st1.tbl;
    
    
    printf("===> delete st2.tbl <=== : \n");
    delete  st2.tbl;
    
    return(0);
    }




    The output is :
    strt :one
    strt :two
    strt :three
    ===> delete []st1.tbl <=== :
    delete strt :three
    delete strt :two
    delete strt :one
    ===> delete st2.tbl <=== :
    delete strt :one
    Abort (core dumped)


    I used the debbger and program fails on ending the function mstr::~mstr() after releasing st2.tbl[0].
    I fail to

    see why.

  14. #14
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Hi,

    You have a situation like this:
    Code:
    st2.tb1 -------> mstr ----> char
                                char
                                char
                     mstr ----> char
                                char
                     mstr ----> char
                                char
                                char
                                char
    A pointer to an array points to the first element of the array. When you delete st2.tb1, you have two incorrect deletes that execute. st.tb1 points to the first mstr, which is deleted, but before it is goes out of existence, it incorrectly calls delete, which deletes only the first char of the char array:
    Code:
    st2.tb1 -------> mstr ----> char
                                char
                                char
                     mstr ----> char
                                char
                     mstr ----> char
                                char
                                char
                                char
    So, I think you end up chopping the head off two arrays, which apparently causes the program to abort. Why it aborts instead of just continuing on with a memory leak, I don't know.

  15. #15
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    printf()? strcpy()? At least include <cstdio> and <cstring>.

    Code:
    strt  st1, st2;
    //...
    delete  []st1.tbl;
    //...
    delete  st2.tbl;
    You're deleting the same thing here. Make up your mind. Is it an array or not? And that's the sort of thing you would put in a destructor.

    BTW, what's a debbger?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21