Mysteries related to char array and char pointers...? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

18th Feb 2018, 7:04 PM
Fabricated Reality
Fabricated Reality - avatar
2 Answers
+ 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.
19th Feb 2018, 1:58 AM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
+ 2
Thank you that clears a lot of confusion ☺
19th Feb 2018, 3:50 AM
Fabricated Reality
Fabricated Reality - avatar