So, I wrote a function which resizes a Two-Dimensional array.
void resizeArray(int **&arr, short &arrSize1, short* &arrSize2, const int &amount)
{
int** arrTemp = new int*[arrSize1 + 1]; // Creating a 2D array
for (short i(0); i < arrSize1 + 1; i++) // For each arrTemp[i] an array is created
arrTemp[i] = new int[(arrSize2[i] == 0 ? 1 : arrSize2[i])];
for (short i(0); i < arrSize1; i++) // Copying old values to the new BIGGER temp array
for (short i2(0); i2 < (arrSize2[i] == 0 ? 1 : arrSize2[i]); i2++)
arrTemp[i][i2] = arr[i][i2];
for (short i(0); i < arrSize1; i++)
delete[] arr[i];
if (arrSize1) // The first time this function is ran arrSize1 is 0 and arr is a nullptr
{
delete[] arr;
arr = nullptr;
}
arr = new int*[arrSize1 + 1]; // Creating the new BIGGER arr
for (short i(0); i < arrSize1 + 1; i++) // Creating the sub-arrays(or second dimension)
arr[i] = new int[(arrSize2[i] == 0 ? 1 : arrSize2[i])];
for (short i(0); i < arrSize1 + 1; i++) // Copying from arrTemp to arr
for (short i2(0); i2 < (arrSize2[i] == 0 ? 1 : arrSize2[i]); i2++)
arr[i][i2] = arrTemp[i][i2];
for (short i(0); i < arrSize1 + 1; i++) // Deleting arrTemp
delete[] arrTemp[i];
delete[] arrTemp;
arrTemp = nullptr;
for (short i(0); i < (arrSize2[arrSize1] == 0 ? 1 : arrSize2[arrSize1]); i++)
arr[arrSize1][i] = amount; // Setting the newly created sub-array to a value
}
The code above works perfectly - the only problem is when I run Code Analysis it says Warning (Memory Safety) C6001 - '*arrTemp[i]' is not initialized.
I don't quite understand why it thinks that it isn't initialized - I also have function like this for 3D arrays(of course everything with dynamic memory allocation) and it doesn't show any problem there.
I tried fixing it several times, but no avail: 1. Initializing to nullptr after the new int*[] is done; 2. Initializing the values of the 2D array to 0 after the loop is done; 3. A few other stupid things.....
So, is it bug in Visual Studio(which I'm using by the way :)) or is it something in my code that I can't find out?
P.S. Added comments;
Your code generates this warning because when you build your
arrTemp
you allocatearraySize1 + 1
sub-arraysbut assign meaningful values only to
arraySize1
of those sub-arraysAfter that all entries like
arrTemp[arrSize1][i2]
still contain garbage.Later you do
which attempts to read garbage from
arrTemp[arrSize1][i2]
. Hence the warning.