Are these both same methods (initializing const char)?
1:
2:Code:char c[] = "Hello";
Code:char *c="Hello";
Are these both same methods (initializing const char)?
1:
2:Code:char c[] = "Hello";
Code:char *c="Hello";
No they're not the same.
One is an array, the other is a pointer.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
The first declares c to be an array of char, and initialises its content to "Hello". Since the number of elements of c was not explicitly specified, it follows that of the initialiser, i.e., c is an array of six char. The contents of c are modifiable, although of course you cannot assign to c itself since c is an array.
The second declares c to be a pointer to char, then initialises c to point to the first character of the string literal "Hello". Note that this means that the code is likely to be poorly written: c should have been declared as a pointer to const char instead so as to avoid accidentally attempting to modify a string literal, which would result in undefined behaviour. However, you can assign to c itself since c is a non-const pointer.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I didn't get the meaning of these two lines: 1: " you cannot assign to c itself " & 2: you can assign to c itself since c is a non-const pointer
Try to compile and observe the error message:Originally Posted by gaurav#
Code:#include <stdio.h> int main(void) { char c[] = "Hello"; char d[] = "World"; c = d; printf("%s\n", c); return 0; }Compile and run:Originally Posted by gaurav#
Code:#include <stdio.h> int main(void) { char *c = "Hello"; char d[] = "World"; c = d; printf("%s\n", c); return 0; }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)