0

Say I create an array of pointers like so:

char ** arr[]

My understanding says this creates an array of pointers, each pointer points to an array of chars.

Then I want to set 8 such arrays for example, each array having 10 chars in it, so I do this:

arr = new char*[7];
for(int i = 0; i<9; i++)
    arr[i] = new char[0];

this works, but my issue is I can't wrap my mind behind how it works.

In my mind when I write arr = new char*[7]; that means my array of pointers will have room for 7 pointers, but in actuality all 8 pointers work fine for me so I don't understand why putting 7 there works, whereas putting 6 for example crashes the program.

and then there's arr[i] = new char[0]; which again confuses me, cause to me that seems as if I'm creating arrays that can only contain 0 chars, yet when I try to input a 9 char string using strcpy it works fine.

Does the new function automatically resize the arrays? is there something else here I'm simply not understanding?

gaurav bharadwaj
  • 1,669
  • 1
  • 12
  • 29
  • 3
    Undefined behaviour, to go out of bounds. It might work, it might not. Best to just stay within bounds, as this often leads to problems in code. – ChrisMM Nov 27 '20 at 13:11
  • 1
    `new char[0]` returns the address of an empty array. (A `nullptr`? An empty object with at least 1 byte?) I'm not sure whether this allocates any storage. [Arrays of size 0](https://stackoverflow.com/a/6180200/7478597) are not allowed in C++ but with `new` they are. However, this array cannot store anything. Writing to any element goes out of bound... – Scheff's Cat Nov 27 '20 at 13:12
  • Out of curiosity, I made an [**MCVE on coliru**](http://coliru.stacked-crooked.com/a/11fced0e3e5f48f4). It's funny to see that the g++ compiled code allocates in fact addresses which appear consecutively with a distance of 32 bytes. That might be for a reason but I don't know which. It could be for alignment, for the kind how the heap is organized, and there might or might not be administrative data around these addresses which may never be corrupted or will crash your appl. sooner or later. Finally, out-of-bound writing to arrays is U.B., and "it seems to work" is only one kind of U.B. – Scheff's Cat Nov 27 '20 at 13:24
  • "my understanding says this creates an array of pointers, each pointer points to an array of chars" Not really. This doesn't create any array. This declaration together with the next fragment makes an invalid program. Please post a [mcve]. – n. m. could be an AI Nov 27 '20 at 14:35
  • `char**arr[]` is a pointer-to-pointer-to-pointer-to `char`. It’s a nightmare. Don’t be a [three star programmer](https://wiki.c2.com/?ThreeStarProgrammer). – Pete Becker Nov 27 '20 at 14:44

0 Answers0