Address-less pointers
I understand how pointers work but, what is happening with the const char*? I understand the purpose for it (to make a string) but is merely a "false friend" of sorts. If it is a pointer then what is happening here, it is not refering to address. Any explanation would be awesome. Thank you for your feedback
6/20/2018 8:22:35 PM
Bradley
8 Answers
New AnswerA pointer its the adress of first char. Strings (or better C like strings) are an array of char BUT they are terminated by a 0 value char... Example const char* y= "Hello"; Assume that 0x1 is the value of y (or the adress of first char 'H'), you will have: 0x1 'H' 0x2 'e' 0x3 'l' 0x4 'l' 0x5 'o' 0x6 0 ( is a zero value) if y would be an char* you can modify any char like: y[1]='a'; // Now y point to 'Hallo' string but with const char* you cannot do it
A pointer an an array are the same thing; an array is a pointer which points to the first element of the array. That means a char* is an array of chars, just like {1, 2, 3} is an array of ints (or int*). It has an address and it is a pointer and you can use it for any pointer things you want. char* y = "Hello world"; printf("%c\n", *y); y++; printf("%c\n", *y); will print "H", then "e". `const char*` is a bit different, the compiler will do some optimizations on it and place it in special parts of memory if it can.
You have to read it like "a pointer to const char"... Because it point to a const variable, you cannot dereference the pointer for modify pointed value: char c= 'c'; const char* cp= &c; char b= *cp; // all ok *cp= 'd'; // error
Yeah, but why is the pointer used with the char value to make a string if I go char* y = "Hello world" it displays the entire sentence how does the pointer make a difference? Thank for answering
Technically the only difference between pointer and array is that an array dont support pointer arithmetics (its safer think an array like an constant pointer )... Just for clearify