I wanted to create a 2D array similar to...
[1 8 7 1]
[8 9 6 0]
[5 8 4 5]
[3 2 4 3]
I tried... int arr[4][4] = {1,8,7,1,8,9,6,0,5,8,4,5,3,2,4,3};
and int arr[4][4] = {{1,8,7,1},{8,9,6,0},{5,8,4,5},{3,2,4,3}};
I printed them and they came out as I wanted.
My question is, why does it print 8 when I do: cout << arr[0][4] << endl;
It prints it as if it was in the same row, when it should be out of bounds. Did I miss a simple concept?
In terms of memory layout, a matrix is one long array with no padding between each element. It's effectively equivalent to this:
1 2 3 4 5
// This:
int Array[3][3];
// ...is actually this:
int Array[9];
Knowing this, we can easily compute the destination: Array + (Column-Index + Row-Index). I'm not 100% sure about why this is, but I've thought of a few possible reasons:
1. Book-keeping is easier and less stack space is required to keep track of each row.
2. Avoids memory fragmentation (if dynamically allocated).
3. Makes more effective use of the CPU & code caches.
4. Easier to optimise.
Which is why there are things like constants and pre-compiler directives.
Did you know that the only reason out of bounds would crash your program is if you run into memory that another program is using? Just becuase you do this:
1 2
int array[4];
cout << array[4];
Doesn't mean your program will crash. It's up to you to make sure you stay in bounds. Sorry if you already know that...
@LowestOne
Let's say you have a 3x3 matrix on a piece of paper. If you search for the location 1,4, it is not possible because it is off the matrix. You can't do it on the because it doesn't work like that in C++. When I check to see if that location is NULL, it isn't. That is what I meant by out of bound.
That's impossible. An address is NULL only when it's 0. Since arrays are pointers to the first element of a sequence, the first element may be at address 0 (and crash the program with a segmentation fault if you try to write to it), but an element even one place away from the first can't have address 0
Though I don't think you can actually create an array starting at NULL