The comparison is not fair: code snippets are not equivalent.
You have to compare either
int *p;
p = 19;
cout << "p val"<< *p << endl;
cout << "p addr" << p << endl;
char *s;
s = 'a';
cout << "s val"<< *s << endl;
cout << "s addr" << s << endl;
Compiler output:
[...]: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
p = 19;
^~
[...]. error: invalid conversion from ‘char’ to ‘char*’ [-fpermissive]
s = 'a';
^~~
or
const int ia[] = {1,2,3};
int *p;
p = ia;
cout << "p val"<< *p << endl;
cout << "p addr" << p << endl;
char *s;
s = "alpha";
cout << "s val"<< *s << endl;
cout << "s addr" << s << endl;
Compiler output
[...]: error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive]
p = ia;
^~
[...]. warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
s = "alpha";
^~~~~~~
In the above case (b snippets), the compiler actually consider
char
somehow special (I guess it is a
C
legacy).
[update]
Quote:
But what i do not know is why a regular integer pointer cannot point to a const integer.
A pointer
can point to an integer constant, for instance:
const int myconst = 10;
const int * p = &myconst; printf("Address = %p, value = %d\n", p, *p);
However you cannot arbitrarly assign an address to it (as in your example):
const int * p = 19;
is plainly wrong.
Quote:
My first assumption is that , allowing so would allow the value of the const int to be changed through the pointer
This is fairly correct: you can assign
the address of a integer const only to
a pointer to integer const (NOT a const pointer).
Quote:
econd assumption is that a const pointer is to be used to point to a const variable
Nope.
- A pointer to integer const is to be used to point a integer const.
- A const pointer is a pointer whoose value (that is the address it points) cannot be changed.
E.g.
const int myconst = 10;
const int * p = &myconst; int i = 0;
int j = 0;
int * const q = &i; *q = 50; q = &j;
[/update]