Jin
Jin

Reputation: 1948

Strange behaviours of pointer to constant in C

I have some questions about strange behaviours of pointer to constant in C.

1.

int x = 1;
const int *ptr = &x; 
x = 2;
printf("%d %d",*ptr, x);

Since pointer ptr points to const int, I expected an error in the third line. (Because "1" is already saved in the pointer ptr and the value in the pointer cannot change since I have added "const"!)

2.

double rates[3] = {0.1,0.2,0.3};
const double *ptr = rates;
ptr[2] = 99.99;

From the second line, ptr is the address of rates[0]. I expected no error to occurs from the third line since only *ptr = rates[0] is const double!

Why does such things happen?

Upvotes: 0

Views: 99

Answers (3)

sjsam
sjsam

Reputation: 21965

Remember

const double *ptr; // Remember it like (const double) <- *ptr;

means ptr is pointing to const double, which just means you can't use pointer itself to change the data pointed to. However if the original data itself is not constant, you may use any other agent to modify the value like you did in

Case 1

const int *ptr = &x; 
x = 2; // You use x itself to change the value

Since pointer ptr points to const int, I expected an error in the third line.

You won't get an error, because you're not changing x through pointer. If you do

*ptr=2; //you get an error

Now for Case 2

I expected no error to occurs from the third line

const double *ptr = rates;
ptr[2] = 99.99;

This is the opposite of the first case, you used pointers to change constant data, Had the line been

rates[2] = 99.99;

you would have got no errors.

Upvotes: 3

Michel
Michel

Reputation: 143

Const simply tells the compiler not to allow you to directly change the value of that variable. It does not make it impossible to change it. You can still change the value with pointers, like you did.

When you use const with pointers, you simply tell the compiler not to allow you do change the value of that pointer, not the value stored in the array.

Upvotes: 1

M.M
M.M

Reputation: 141554

x is not const. So x = 2; is OK.

const int *ptr; does not mean "ptr points to const int". It means "ptr may point to an int which may or may not be const; and you are not allowed to use *ptr to write to that int."

Because "1" is already saved in the pointer ptr

No, the thing saved in the pointer is the address of a memory location. 1 is saved in the memory location that the pointer holds the address of.

only *ptr = rates[0] is const double

That makes no sense. ptr[2] means *(ptr + 2) ; and using + 2 on a const double * yields another const double * pointing to a different memory location.

Upvotes: 3

Related Questions