Question #157609

Write a piece of code that dynamiccaly creates 1) a 1d char array of size 100 and 2) a 2d array having 4 rows where the first row has only one cell, second row has two cells, third row has three cell, fourth row has four cells. Now write the code to delete the arrays.


Expert's answer

int main()
{
    char *array1d = new char[100];

    char **array2d = new char*[4];
    for (int i = 0; i < 4; i++) {
        // for i=0, sets (0+1)=1 element to 0th row, and so on
        array2d[i] = new char[i + 1];
    }

    delete[] array1d;
    for (int i = 0; i < 4; i++)
        delete[] array2d[i];
    delete[] array2d;
}

LATEST TUTORIALS
APPROVED BY CLIENTS