+ 6
Mysteries related to char array and char pointers...?
1. char ch1[] = "text"; 2. char* ch2 = "text"; QUestion 1: I know about pointers and arrays but .... Why is ch1[0] ='a' valid but ch2[0] ='a' not? Question 2: And since ch2 is a pointer it must contain an address....Can a pointer hold the address of a string literal!? Question 3: Do we need to have a '\0' when we initialize a char array or pointer to a string literal?
2 Respostas
+ 6
Q1. Since ch1 is an array, when we assign a string literal, memory is allocated for 5 characters (4 letters + one null character to indicate the end of string) and the letters in the string are copied here. This is your own memory area and you can change these characters in the array.
All the literals/constants are stored in data section of the program memory layout. when you assign a string literal to a pointer, it contains address which refers to the data area. Trying to change a constant is not valid so you cannot change string using ch2.
Q2. Yes, a pointer can have address of a string literal, if you try to modify it, unintended results happen
Q3. When you initialize a string literal to a char array no need to explicitly specify a null character.
However if you initialize it using a char array literal i.e {'a','b', '\0'} we should add a null character.
+ 2
Thank you that clears a lot of confusion ☺