This is a program of jagged array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include<iostream>
using namespace std;
void display(int **Ptr, int row, int *p);
int main() {
int r = 0, c = 0;
cout << "Enter Rows in Array: "; cin >> r;
int*ptr = new int[r];
int**P = new int*[r];
for (int i = 1; i <= r; i++)
{
cout << "Enter the Cols in Row#" << i << ": ";
cin >> c;
ptr[i - 1] = c;
P[i] = new int[c];
for (int j = 0, m = 1; j < c; j++)
{
cout << m++ << "- ";
cin >> P[i][j];
}
}
display(P, r, ptr);
delete[] P;
delete[] ptr;
system("pause");
return 0;
}
void display(int **Ptr, int row, int *p)
{
for (int i = 1, m = 1; i <= row; i++)
{
cout << "Elements of Row " << i << ": ";
for (int j = 0; j < p[i - 1]; j++)
{
cout << Ptr[i][j] << " ";
}
cout << endl;
}
}
|
If you run the program, it will give you an output (for example, this is one output I got for a random set of values)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
Enter Rows in Array: 3
Enter the Cols in Row#1: 2
1- 1
2- 2
Enter the Cols in Row#2: 4
1- 3
2- 2
3- 1
4- 6
Enter the Cols in Row#3: 3
1- 2
2- 3
3- 0
Elements of Row 1: 1 2
Elements of Row 2: 3 2 1 6
Elements of Row 3: 2 3 0
|
And at the end, I got this error, once the program was executed,
1 2
|
Heap Corruption Detected: after Normal block (#189) at 0x00AFE578.
CRT detected that this application wrote to memory after end of heap buffer
|
It clearly shows that there was some issue with heap memory to which memory was allocated and something like that.. but my question is, why did it allow the program to run at first?
At Line Number 14,
When the loop controlling variable will be i = 3 (last iteration), then I am clearly allocating memory to a garbage index of the array (if you see, my double pointer is pointing to a array of pointers of size 3. That is, its indexes will be 0 1 and 2... 3rd index would be of garbage)
But still, it allows the allocation of memory at that index and even displays the values when I try to access that column in the Display function. Why does it do that? Can anyone explain?