jwqwerty - 1 year ago 51
C Question

# 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?

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.