Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const and pointers in C

Tags:

The use of const with a pointer can make the pointee not modifiable by dereferencing it using the pointer in question. But why neither can I modify what the pointer is not directly pointing to?

For example:

int a = 3;
const int* ptr = &a;
*ptr = 5;

will not compile. But why does

*(ptr + 2) = 5;

also not compile? I'm not changing what the pointer is pointing to.
So do we have to say that using const with a pointer in such a way not only makes not modifiable what the pointer is pointing to (by dereferencing the pointer) but also anything else, to which the adress we get using the pointer?

I know that in the example I'm trying to access not allocated memory, but this is just for the sake of discussion.

like image 471
Root149 Avatar asked Dec 21 '14 11:12

Root149


People also ask

What is the difference between constant pointer and pointer to a constant?

In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.

What is the use of const pointer?

A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.

Can we declare a pointer variable as constant in C?

We can create a constant pointer in C, which means that the value of the pointer variable wouldn't change. We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const).


2 Answers

ptr +2 simply has the same type as ptr namely is a pointer to a const object.

Pointer arithmetic supposes that the object that is pointed to is an array of all the same base type. This type includes the const qualification.

like image 93
Jens Gustedt Avatar answered Sep 24 '22 03:09

Jens Gustedt


The non-modifiability introduced by const depends on where const is written.

If you write

const int * ptr = &a;

(or int const * ptr = &a;), the const refers to the pointee, so using the pointer for writing to the destination is forbidden.

(OTOH, if wou wrote

int * const ptr = &a;

you couldn't modify ptr.)

In your case, everything involving writing to the destination is forbidden.

This includes *ptr and ptr[0] (which are equivalent), but also everything involving a modification of the destination address, such as *(ptr + 2) or ptr[2].

like image 30
glglgl Avatar answered Sep 22 '22 03:09

glglgl