Thread: Question about pointers #3

  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,897
    >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,897
    >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, 01:31 AM
  2. A question on Pointers & Structs
    By FJ8II in forum C++ Programming
    Replies: 4
    Last Post: 05-28-2007, 10:56 PM
  3. simple pointers question
    By euphie in forum C Programming
    Replies: 4
    Last Post: 05-25-2006, 01: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, 11:04 AM