5

I have created an empty char multidimensional array, but when I try to change a specific value, it sometimes duplicates to another space in the array.

Example:

#include <iostream>
using namespace std;

char arr[2][2] = { 0 };

int main ()
{
    arr[2][0] = 'A';
    for(int i = 0; i < 3; ++i)
    {
        for(int j = 0; j < 3; ++j)
        {
            cout << "arr[" << i << "][" << j << "] = " << arr[i][j] << endl;
        }
    }
}

Output:

arr[0][0] =
arr[0][1] =
arr[0][2] =
arr[1][0] =
arr[1][1] =
arr[1][2] = A
arr[2][0] = A
arr[2][1] =
arr[2][2] =

The character A should only appear in [2][0] but it also appears in [1][2]. This happens only in these spaces:

[1][0], [2][0], [0][2], [2][2]

I was able to recreate this with a bigger array, but I can't say the specific values.

I have tried defining inside the main() function but it created another problem, random characters started appearing in random locations of the array.

I tried initializing the array with char arr[2][2] = { 0 }, but it didn't help.

asynts
  • 2,213
  • 2
  • 21
  • 35
aaaeka
  • 75
  • 5
  • 1
    Unrelated to your problem, but this is a very well written first question. You've given us a minimal verifiable complete example and what you're expecting vs. your actual output. I look forward to seeing more of your contributions here! – scohe001 Oct 19 '18 at 14:35
  • the C++ idiom to [initialize](https://stackoverflow.com/a/31114758/1132334) a multi-dimensional, constant-sized array is `char arr[2][2] = { };`. another option is `std::fill` – Cee McSharpface Oct 19 '18 at 14:43

3 Answers3

6

When you declare char arr[2][2] = { 0 };, that's a 2x2 array. Which means it's indices go from 0 to 1. You're writing into index 2, which is outside of array bounds.

Kon
  • 4,023
  • 4
  • 24
  • 38
2

There is probably some memory bashing happening. When you declare an array as char arr[2][2] = { 0 }; array of two arrays of size two of char. Which means 4 char elements.

You can access them as

arr[0][0];
arr[0][1];
arr[1][0];
arr[1][1];

For your code to work you need to buff up the size of the array to char arr[3][3] = { 0 };

To answer your question why are they duplicated. The memory continues when you allocate char arr[2][2] it will allocate space for 4 elements and it might be the same as char arr[4].
When you try to access an element out of the bounds of your array the behavior is undefined at it resulted in accessing the memory of the second array.

Petar Velev
  • 2,305
  • 12
  • 24
0

That's because you're going past your array. An array of char arr[2] only goes from 0 to 1 (that's 2 values). Similarly, for your arr[2][2] you can also only use 0 and 1 as array index.

Try this instead:

char arr[3][3] = { 0 };

Now the array index can go from 0 to 2.

Blaze
  • 16,736
  • 2
  • 25
  • 44