Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Pointer Question

1. ## Pointer Question

Hi,

Ive been given this code:

Code:
```int i=0, j=0, *k=0, *l=0;
k = l;
l = &i;
j = *k;```
Ive also been told that this code crashes. The question is, explain the cause of the crash, and correct the program by rearranging the istructions without modifiying them.

Can someone help me to understand why it is crashing. Ive been told that line 4 is the problem, and that reversing line 2 and three fixes the problem.

Ive even been told it has something to do with dereferencing, but for the life of me I cant find any information or tutorials online that will help me understand what is going on.

Can anyone explain this to me?

• You are correct that line 4 is the issue. What is happening there is that k is pointing to memory address zero. So this line `j = *k` says assign the data at the memory address stored in k to the variable j.

And memory address zero is considered null in the C and C++ and you cannot de-reference a pointer at that address. So think about how re-arranging the instructions could prevent this problem and where k is not null.

Reversing the two lines like you are thinking will solve the problem. Is it clearer why doing so fixes the problem?

• Im still not 100% on this though. I think its the second line that is confusing, is it setting the value of the pointer k equal to the value of the pointer l? In which case setting k equal to 0.

Is it correct to say that k isnt then updated in line three, becuase the value of l is changed after k has been equated to the value of l. For example:

l = 3
k = l;
l = 5;

Would the value of k be 3 and not 5?

• Originally Posted by spadez
Im still not 100% on this though. I think its the second line that is confusing, is it setting the value of the pointer k equal to the value of the pointer l? In which case setting k equal to 0.

Is it correct to say that k isnt then updated in line three, becuase the value of l is changed after k has been equated to the value of l. For example:

l = 3
k = l;
l = 5;

Would the value of k be 3 and not 5?
Correct, k would be equal to 3.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•