Thread: What the????

  1. #1
    Registered User Mr_Jack's Avatar
    Join Date
    Oct 2003

    What the????

    I'm seriously confused. When I asked for help with making a two dimensional array of the free store, some people gave some method using a loop that I didn't understand. But when I was messing around with pointers, I discovered that I could make a perfectly functioning two dimensional array on the free store very, very easily:
    char * foo[3] = {new char[3]};
    What's going on? Why don't people just use this method

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >Why don't people just use this method
    Because you have an array of three pointers to dynamic arrays. In other words, you can resize any of the rows, but you can't add any more. You're stuck with three. Sometimes this is what you want, but most of the time it isn't, that's why you don't see it very much.
    char * foo[3] = {new char[3]};
    This creates an array of three pointers to char and initializes the first of them with dynamic memory, the other two are initialized to NULL. So don't be surprised if your program segfaults when you try to use foo[1] and foo[2].
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    May 2003
    That array is not on the free store-- it's on the stack. It creates an array on the stack of 3 pointers to char.

    In fact, according to gcc3.2, the code doesn't work as you would expect. I compiled this program:
    #include <iostream>
    int main()
      char* foo[3] = { new char[3] };
      std::cout << (void*) foo[0] << std::endl;
      std::cout << (void*) foo[1] << std::endl;
      std::cout << (void*) foo[2] << std::endl;
    And this was my output:

    $ ./a.out

    It only initialized the first element of the array. On MSVC6, it doesn't even compile. I'm not sure how this works for you at all. Which compiler are you using?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    You can allocate a 2D array in one step, providing the minor dimension is a constant.

    char (*foo)[3] = new char[8][3];
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed