Char Pointers

I'm trying to work out whats the difference between all these char's and consts and what not. Searched a lot but I'm unsure about a few things whilst experimenting with char pointers.
A topic on Stackoverflow explained a few of them:


char* the_string : I can change the char to which the_string points, and I can modify the char at which it points.

const char* the_string : I can change the char to which the_string points, but I cannot modify the char at which it points.

char* const the_string : I cannot change the char to which the_string points, but I can modify the char at which it points.

const char* const the_string : I cannot change the char to which the_string points, nor can I modify the char at which it points.


What does he mean for each one? Especially char* const I don't know how to use that one Can someone give me an example of some code for each one please i.e what is valid and invalid?

Thanks
Last edited on
I do not understand what for example this statement "I can change the char to which the_string points, and I can modify the char at which it points.
" means.

I would rewrite the statements the following way

char* the_string : I can change the char to which the_string points, and I can modify the pointer itself that is I can assign a new value to it..

const char* the_string : I can not change the char to which the_string points, but I can modify the pointer itself.

char* const the_string : I can change the char to which the_string points, but I can not modify the pointer itself.

const char* const the_string : I cannot change the char to which the_string points, and I can not modify the pointer itself..


Last edited on
I still don't understand -> Some code examples would help...
I.e What's valid and invalid with these types etc

If you cannot change *char or const char* (the string literals) surely they are the same thing then? I need to read the Pointers section again.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//After declaring C-string, an example of:
//   1) modifying what is being pointed at
//   2) modifying the pointer itself
char single_char = '!';

char* C_string="Hello";
  *(C_string+3) = 'd';                //Valid
  C_string = &single_char;            //Valid

const char* C_string2 = "there";
  *(C_string2+1) = 'e';               //Error
  C_string = &single_char;            //Valid

char* const C_string3="buddy";
  *(C_string3+4) = 'i';               //Valid
  C_string3 = &single_char;           //Error

const char* const C_string4="pally";
  *(C_string4+1) = 'i';               //Error
  C_string3 = &single_char;           //Error 


A rule of thumb I've heard is to remember that the qualifier affects what is to the left of it.
Topic archived. No new replies allowed.