Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Characters duplicate in a multidimensional array

Tags:

c++

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.

like image 373
aaaeka Avatar asked Oct 19 '18 14:10

aaaeka


People also ask

How do you find duplicates in a 2D array?

Here's a brute-force straight forward way of counting duplicates. Turn the 2d array into a 1d array ( List<Integer> ), then loop through the 1d array counting the duplicates as you find them and removing them so you don't count them more than once.

How do you get unique values in a multidimensional array?

A user-defined function can help in getting unique values from multidimensional arrays without considering the keys. You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys.

What is an example of a multidimensional array?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.


1 Answers

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.

like image 76
Kon Avatar answered Sep 23 '22 17:09

Kon