Possible Duplicate:
What is the difference between char * const and const char *?
const char * const versus const char *?
as we define a function in c,we may use (const char *str) , (char const *str) or (char *const str) as a variable.What's the difference among them?
The first two are equivalent, const char *str
and char const *str
both declare str
to be a pointer to a char constant (that means that the char itself shouldn't be modified), the third one, char *const str
declares str to be a constant pointer (meaning that once assigned it shouldn't be changed) to a char
(which itself can be modified freely).
An interesting article regarding how to read type declarations is here, in case you want to check it.
char const * str
and const char * str
are the same, as const applies to the term on its left or, if there isn't a type on the left side, to the right one. That's why you get a double const error on const char const *
. Both are pointers on a constant char. You can change the value of the pointer, but not the dereferenced value:
const char * my_const_str;
my_const_str = "Hello world!"; // ok
my_const_str[0] = "h"; // error: my_const_str[0] is const!
char * const
on the other hand is a constant pointer. You cannot change the pointer, but you can change the value dereferenced by the pointer.
char * const my_const_ptr = malloc(10*sizeof(char));
my_const_str[0] = "h"; // ok
my_const_str = "hello world"; // error, you would change the value of my_const_str!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With