0

I did'nt understand here in this code i was reading a book and then

const char *q="Hello"; //string is fixed pointer is not
*q='M'// error
q="bye"; //works

char * const t="Hello"; //string is fixed pointer is not
*t='M'// works
t="bye"; //error

so my question is in first if string is fixed then how q="bye" is working

Edited by mike_2000_17: Fixed formatting

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by nbaztec
0

lets make it a bit simpler:

int foo = 5;
const int cfoo = 10;
const int* p = &foo;  //Pointer to constant
//Since it's a pointer to a constant, *p = 10 won't work
int* const p = &cfoo; //Constant pointer (initialization necessary)
//Since it's a constant pointer: 
//1. It should be initialized upon declaration
//2. It can't be reassigned another address to point.

Hope that clears up. See: http://www.codeguru.com/forum/showthread.php?t=357915

0

But string being a constant can't be changed q="bye" is changing "hello" to "bye" so how it's constant

0

Pay attention closely, the string is *not* changing, the pointer is. To change the string you'll have to dereference the pointer.( *ptr = "newString" )

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.