4.6Strings: Declaration, Initialisation and Input/Output
Covers IGNOU MCS-201 §4.7, 4.8
Names, addresses and messages are text. C has no separate string type: a string is a character array that ends with a special marker. Understanding that marker, the null character, explains every rule and every bug involving strings in C.
What a string is
The null character '\0' marks the end of a string. It is different from the digit character '0' (code 48). A string of n visible characters therefore needs n + 1 bytes.
'A' is one character (1 byte of data); "A" is a string of two bytes, 'A' and '\0'.
Declaring and initialising strings
Declaration
Bytes
Valid string?
char str[] = "UNIX";
5
Yes: size counted automatically, '\0' included
char str[5] = {'u','n','i','x','\0'};
5
Yes
char str[9] = "unix";
9
Yes: the unused 4 bytes are also '\0'
char str[4] = "unix";
4
No: exactly fills the array, no '\0'
char str[4] = {'u','n','i','x'};
4
No: no '\0'
char str[3] = "unix";
—
Invalid: too many characters
A string cannot be assigned with = after its declaration (s = "hello"; is an error for an array s); use strcpy from <string.h>.
Printing and reading strings
printf("%s", name) prints characters up to, but not including, the '\0'. puts(name) prints the string followed by a newline.
For input there are two standard tools:
Function
Reads
Notes
scanf("%9s", name)
One word: stops at the first space, tab or newline
No & (the array name is already an address). Always give a maximum width: array size − 1
fgets(line, sizeof line, stdin)
A whole line, including spaces
Never overflows; keeps the newline '\n' if it fits
Key takeaways
A string is a character array terminated by '\0' (value 0, not the digit '0').
n characters need n + 1 bytes; a string constant initialiser adds the '\0'.
%s in scanf reads one word; fgets reads a line and limits the length.
printf("%s") and puts print up to the '\0'.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain the difference between char a[] = "CAT"; and char b[] = {'C', 'A', 'T'};, and what happens if each is printed with %s.
Show worked answer
a has 4 elements: ‘C’, ‘A’, ‘T’ and the null character '\0' added by the string constant, so it is a valid string and printf("%s", a) prints CAT. b has exactly 3 elements and no '\0', so it is a character array but not a string; printf("%s", b) keeps reading memory past the array until it happens to find a 0 byte, which is undefined behaviour and may print extra garbage characters.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/arrays-and-strings/strings-declaration-initialisation-and-input-output/ to read this page.