A string is an array of characters ending in '\0', so everything about arrays and pointers applies to strings. Character pointers give a compact way to refer to strings and to handle lists of strings of different lengths.
Two ways to hold a string
Declarations
char country1[] = "INDIA"; /* an array of 6 characters, initialised with a copy of the text */char *country2 = "INDIA"; /* a pointer to a string literal stored elsewhere */
char country1[] = "INDIA";
char *country2 = "INDIA";
What is created
An array of 6 char
A pointer (8 bytes) to a string literal
Can the characters be changed?
Yes: country1[0] = 'i';
No: modifying a string literal is undefined behaviour
Can it refer to another string later?
No: an array cannot be reassigned
Yes: country2 = "CHINA";
sizeof
6
8
Because the literal must not be changed, such a pointer is best declared const char *.
printf("%s", country2) needs the pointer; %s prints characters from that address up to '\0'. *country2 is a single character, the first one, printed with %c.
Each element is a char * pointing to the first character of one string. Compared with a two-dimensional array such as char country[5][11];, which reserves 11 bytes for every row (55 bytes), the strings here occupy only as many bytes as they need, plus one pointer each.
country[i] is the i-th string (use with %s).
country[i][j], or *(*(country + i) + j), is character j of string i. For example, *(*(country + 3) + 2) is the third character of the fourth string: the ‘K’ of “PAKISTAN”.
Key takeaways
char s[] = "…" creates a modifiable array; char *p = "…" points to a literal that must not be modified.
%s takes the pointer; *p is one character.
A string is traversed by moving a pointer until '\0'.
char *list[n] holds n strings of any length; swap pointers to reorder them.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function my_strlen(const char *s) using only pointer operations, and explain why sorting an array of pointers to strings is faster than sorting a two-dimensional character array.
Show worked answer
int my_strlen(const char *s) { const char *p = s; while (*p != '\0') p++; return (int)(p - s); }. The pointer p starts at the first character and advances until it reaches the null character; the difference p - s is the number of characters passed. Sorting an array of pointers exchanges only the pointers (8 bytes each), whatever the length of the strings, while sorting a two-dimensional array must copy whole strings character by character (for example with strcpy) each time two rows are exchanged.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/pointers/pointers-and-strings/ to read this page.