Let’s say I have an array like this:
string x[2][55];
If I want to fill it with “-1”, is this the correct way:
fill(&x[0][0],&x[2][55],"-1");
That crashed when I tried to run it. If I change x[2][55] to x[1][54] it works but it doesn’t init the last element of the array.
Here’s an example to prove my point:
string x[2][55];
x[1][54] = "x";
fill(&x[0][0],&x[1][54],"-1");
cout<<x[1][54]<<endl; // this print's "x"
Because when you have a multi-dimensional array, the address beyond the first element is a little confusing to calculate. The simple answer is you do this:
Let’s consider what a 2d array
x[N][M]is laid out in memorySo, the very last element is
[N-1][M-1]and the first element beyond is[N-1][M]. If you take the address of[N][M]then you go very far past the end and you overwrite lots of memory.Another way to calculate the first address beyond the end is to use sizeof.