-
const const int* ?
I have two doubts.
1) I read my textbook and suddenly noted this anomaly.
Code:
int a[5]{1, 2, 3, 4, 5};
int *p = &a[0];
cout<<p<<endl<<*p
gave an output.
0xfffffe (or somthing like this.).
1
But,
Code:
char a[5] = {'0', '1', '2', '3', '\0',};
char *p = a[0];
cout<<p<<endl<<*p;
gave
0123
0
instead of,
0xffffed
0
This happens only with char. I think this is to make couting of strings easier. [b]But why only for char?[b]
_______________________________________
2) (a)Suppose I want to point to a const int or const char.(pointer may change).
(b)And suppose I want to constantly point to ta varying char variable.
(c)And now suppose I want to constantly point to to a constant variable.
What do I do;(a)
Code:
const int a = 10;
int *p = &a;
or
const int *p = &a; //This would be ambiguos with (c).
const
(b)
Code:
int a= 50;
const int *p = &a;
(c)
Code:
const int a = 40;
const int *p = &a; //ambiguity with (a)
or
const int a = 40;
const const int *p = &a; //const two times ;)
No wonder I never messed with pointers. :D
-
char* and const char* are the types of null terminated strings i.e. c style strings. Therefore overloads of operator << are provided to print the string itself and not the address as another type of pointer would. Its easy to get the address, just cast to void*.
Now const with pointers....
constant int non const pointer....
Code:
const int* var; // or int const* var;
constant int constant pointer
Code:
const int* const var; // or int const* const var;
constant pointer to non constant int
non constant pointer to non constant int
It helps to read them from right to left. i.e. for
const int* const var;
This says var is a const *(ptr) to an int thats const.
Check the FAQ for some further pointer information.
-
Thanks!
Thanks for the quick response.
But i haven't done any casting with pointers?
Explain please?
>Its easy to get the address, just cast to void*.
-
A void* can store an address of any pointer type:
Code:
const char* pstr = "hello world";
cout<<pstr<<endl;
cout<<static_cast<const void*>(pstr)<<endl;
The operator<< is overloaded to display the address for type void*. On the other hand, the operator<< is overloaded to display the string and not the address for type const char*.
Quote:
But why only for char?
...because that's the way it is. Otherwise, the language might be too straightforward and easier to learn.
-
Because char is a character, and with numbers, it's simply not assumed that a pointer to one is actually a pointer to a sequence, as is done with char. It wouldn't make sense.
const int *
This is usually called pointer-to-const, just to avoid the very confusion you're experiencing.