Question about pointers #3

This is a discussion on Question about pointers #3 within the C++ Programming forums, part of the General Programming Boards category; Thanks to the great responses I got for my first two questions, I will post my third and hopefully last ...

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    124

    Question about pointers #3

    Thanks to the great responses I got for my first two questions, I will post my third and hopefully last about this subject. This question has to do with using pointers as an array of arrays or strings. I basically want to know how to properly allocate and delete memory for something like:

    Code:
    char** pArrayList = new char*[2];
    pArrayList[0] = new char[8];
    pArrayList[1] = new char[8];
    
    strcpy(pArrayList[0], "letters");
    strcpy(pArrayList[1], "letters");
    
    delete [] pArrayList[0];
    delete [] pArrayList[1];
    delete [] pArrayList;
    Will this work? If not, how do I do it, using char** type variables has always confused me.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Will this work?
    Yes, that's one way to do it, and it will work just fine. Though a more general way to go about it is with a loop:
    Code:
    // Allocate
    char **pArrayList = new char*[rows];
    for (int i = 0; i < rows; i++) {
      pArrayList[i] = new char[cols];
    }
    
    // Release
    for (int i = 0; i < rows; i++) {
      delete [] pArrayList[i];
    }
    delete [] pArrayList;
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Jun 2004
    Posts
    124
    Where did the variable cols come from? Or are you just using that to represent the idea of columns in a matrix?

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Where did the variable cols come from?
    I was using rows and cols as generic names rather than 2 and 8 as you had.

    >Or are you just using that to represent the idea of columns in a matrix?
    Yes.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array pointers question?
    By ben2000 in forum C Programming
    Replies: 4
    Last Post: 07-26-2007, 02:31 AM
  2. A question on Pointers & Structs
    By FJ8II in forum C++ Programming
    Replies: 4
    Last Post: 05-28-2007, 11:56 PM
  3. simple pointers question
    By euphie in forum C Programming
    Replies: 4
    Last Post: 05-25-2006, 02:51 AM
  4. Very stupid question involving pointers
    By 7smurfs in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 06:15 PM
  5. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 12:04 PM

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