DEV Community

Discussion on: Pointers In C - Definition, Notation, Types and Arithmetic

Collapse
 
pentacular profile image
pentacular

An address is simply a pointer value, and you'll find that replacing 'address of' with 'pointer to', and 'address' with 'pointer value' will simplify things a lot.

you can assign the value of one pointer to another only if they are of the same type

This is not true -- you can assign where there is an implicit conversion (such as from void *), or by using a cast.

When you add an integer (say n) to a pointer, you are not actually adding the integer literally. You are adding n-times the size of the data type of the variable the pointer is pointing to.

This is a clumsy way to think about it.

A pointer is an index into an array.

When you add one to a pointer, you get a pointer to the next item in that array.

When you subtract two pointers, you get the number of items between those two pointers.

Variables are effectively stored in arrays of length one.
Which is why { int i; &i + 1 } is well defined but { int i; &i + 2; } is not.

Since the address it points at is no longer reserved, it causes illegal memory access.

This is not quite true.

A pointer that does not have a null pointer value or points into or one beyond the end of a block of allocated memory has an undefined value, and using that value has undefined behavior.

If you are very lucky your implementation will produce an illegal memory access error.

If you are unlucky it will appear to work perfectly until, one day, it doesn't. :)

Collapse
 
its_srijan profile image
Srijan • Edited

A big thank you for pointing out the mistakes.

An address is simply a pointer value, and you'll find that replacing 'address of' with 'pointer to', and 'address' with 'pointer value' will simplify things a lot.

I wanted to keep this as basic as possible and I think keeping 'address' would remind them what pointers store.

This is not true -- you can assign where there is an implicit conversion (such as from void *), or by using a cast.

I missed this. My bad.

This is a clumsy way to think about it.

Though your explanation on the same is quite well put, I found this way they would never confuse as I did.

A pointer that does not have a null pointer value or points into or one beyond the end of a block of allocated memory has an undefined value, and using that value has undefined behavior.

I meant "illegal memory access" in the sense it would not give a consistent result. But yeah, should have used different words.

I have made the changes. Thanks again.

Collapse
 
pentacular profile image
pentacular

Regarding pointers and addresses :)

I'd say that a pointer variable stores a pointer type value (just like any other variable).

Which may or may not be a pointer to an object.

The address of an object is a pointer value to that object.

So sometimes a pointer variable stores a pointer value that is the address of an object. :)