I know normally, * and & signs. But our teacher gives us an example and she said "Problem occurs here"
int *a1;
int *a2 = new int[100];
a1=a2 //What does this line mean???
delete []a2;
k=a1[0]//she said error occurs here.
I couldn't understand what is a1 = a2 ? and why does error occur?
a1=a2 //What does this line mean???
=
is the assignment operator. This actually assigns the value of the LHS operand to the RHS operand.
Here, this line means, assign the value of a2
to a1
, i.e, this assigns the a2
pointer to a1
. That is, a1
and a2
points to the same memory location.
Now, once you call delete[]
with a1
, it actually frees the memory. Then, accssing either a1[i]
or a2[i]
is same, accessing already free-d memory which invokes undefined behavior.
To help understand, consider the analogy of a glass of juice with two straws into it. Once you have drank the juice via either of the straw, you cannot get anymore juice via the other one.