What the????

This is a discussion on What the???? within the C++ Programming forums, part of the General Programming Boards category; I'm seriously confused. When I asked for help with making a two dimensional array of the free store, some people ...

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

    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:
    Code:
    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
    Posts
    9,796
    >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.
    Code:
    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
    Posts
    161
    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:
    Code:
    #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
    0x8049a78
    0
    0


    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,333
    You can allocate a 2D array in one step, providing the minor dimension is a constant.

    Code:
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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