While I call for printf("\n%1.2f",a.p[1][0]); or printf("\n%1.2f",a.p[1][1]); it perfectly gives me values 3 and -6.1. But, when I call for printf("\n%1.2f",a.p[0][0]); or printf("\n%1.2f",a.p[0][1]); it gives segmentation fault.
What goes wrong?
L B,
I don't agree.
N increases each time I call a.concat. The first time I add {1.2,-2} to a and the second time {3,-6.1}. When I call a.p[1][1], there is no segmentation fault. But when I call a.p[0][1], there is.
It looks like it deletes the value of the array when resizing.
I'm not saying that putting the delete in the code will fix the segmentation fault. But it will fix the memory leak.
One delete for each new
One delete [] for each new []
If we ignore the memory leak for now, let's simplify the code to focus on the cause of the problem.
Look at this simpler version:
1 2 3 4 5 6 7 8 9
int main ()
{
int** a;
a = newint* [2];
a[1] = newint [2];
a[1][0] = 2;
a[1][1] = 22;
printf("%i,%i",a[0][0],a[0][1]);
}
Now do you see that a[0] is not initialised?
This is effectively the same as the original code, with the same error, a[0] doesn't point to anything.
Chervil,
I got your point about memory leak. On the other hand, the following code which takes care of memory leak without line 5 delete a; still gives segmentation fault.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main (){
int** a = newint* [1];
a[0] = newint [2];
a[0][0]= 1;
a[0][1] = 11;
delete a;
a = newint* [2];
a[1] = newint [2];
a[0][0]= 1;
a[0][1] = 11;
a[1][0] = 2;
a[1][1]=22;
printf("%i,%i",a[0][0],a[0][1]);
}
What I learned from you is
1- memory leak
2- each new needs a delete
Thanks