Pointer Array Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • crispin
    New Member
    • Jan 2007
    • 11

    Pointer Array Question

    Hi,

    I was wondering if I can do the following without creating memory problems:

    Create something like -- int * array1 -- as a public member my class

    then initiate it with a new value every time I run a certain function, like this --- array1 = new int[somenumber] ---

    but ONLY delete it in the destructor --- delete [] array1 ---

    If I reinitiate it with a new value before deleting it, what happens to the old memory which it occupies? Also, can I call ---- array1 = NULL --- or does that not work for arrays?

    Thanks a lot,
    Crispin
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    If you allocate new memory for the pointer, then whatever memory it used to point to still exists. This isn't a major problem in small programs, but it is not a practice you should make a habit of. You should always use the delete command to deallocate that memory, or you may run out of memory in larger applications.

    Setting the pointer to NULL will create the same problem. You are changing the location to which the pointer points (in effect, pointing it to nothing), but the data and memory allocated is still embedded in memory.

    If you want to create new data for the same pointer in different functions, make sure you delete the old content before creating new content. If you cannot use delete, consider using an alternate method of having multiple arrays of data.

    Comment

    • crispin
      New Member
      • Jan 2007
      • 11

      #3
      Thanks a lot Ganon, that really clears things up.

      Does the same thing apply for char strings... i.e. if you initiate a char array (unsigned char *b). Do you deallocate the string like an array (delete []b) or like a single pointer (delete b).

      Cheers,
      Crispin

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        I haven't done a lot with character arrays per se, but I imagine they're just like all other pointer arrays - you should use delete [] b.

        Comment

        Working...