1

What is the difference of multidimensional array initialization?

This is 'Longest Common Subsequence' problem.

string str1, str2;
getline(cin, str1);
getline(cin, str2);
int alphaCount[26] = { 0, };
int str1Len = str1.length();
int str2Len = str2.length();
int** arr = new int* [str1Len+1];
for (int i = 0; i < str1Len+1; i++)
{
    arr[i] = new int[str2Len+1];
    //Method One
    for (int j = 0; j < str2Len+1; j++)
    {
        arr[i][j] = 0;
    }
}
for (int i = 0; i < str1Len; i++)
{
    for (int j = 0; j < str2Len; j++)
    {
        int y = i + 1;
        int x = j + 1;
        if (str1[i] == str2[j])
            arr[y][x] = arr[y - 1][x - 1] + 1;
        else
        {
            if (arr[y][x - 1] > arr[y - 1][x])// using uninitialized memory ERROR
                arr[y][x] = arr[y][x - 1];
            else
                arr[y][x] = arr[y - 1][x];
        }
    }
}
cout << arr[str1.length()][str2.length()] << "\n";


// Method Two
// Not Error
for (int i = 0; i < str1Len + 1; i++)
{
    for (int j = 0; j < str2Len + 1; j++)
    {
        arr[i][j] = 0;
    }
}


// Method Three
//global valiable, Not Error
int arr[1001][1001];

Why Method One has error message warning C6001: using uninitialized memory .

What is the difference between method 1 and method 2?

gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

0

If there are more elements than numbers in the list, C++ pads the list with zeros. Thus this static array:

int alphaCount[26] = { 0, };

will have all its members initialized to zeroes (explicitly setting the first element to zero, and letting the others get automatically initialized).

This:

int** arr = new int* [str1Len+1];
for (int i = 0; i < str1Len+1; i++)
{
    arr[i] = new int[str2Len+1];
    for (int j = 0; j < str2Len+1; j++)
    {
        arr[i][j] = 0;
    }
}

will also initialize all elements of the array to 0. However, in this case, the array is a 2D array, and is dynamically allocated (don't forget to free it afterwards). Typically you should check if new succeeded.

Note: Static array vs. dynamic array in C++.


The second method will initialize all the elements of the 2D array to zero, by using a double for loop.


The third method will initialize the global array's elements to zeroes, since Why are global and static variables initialized to their default values?

gsamaras
  • 71,951
  • 46
  • 188
  • 305