Abstract
- Basically an array of characters that ends with the null terminator
\0
String termination
Always ensure strings end with an null terminator
\0
, or you will encounter unexpected behaviour when using string methods.In many cases, a string that is not properly terminated with
\0
will result in illegal access of memory like Stack Overflow.The issue shown in the picture can be resolved by assigning the string using double quotation marks -
"apple"
, or, less preferably, by usingstr[5] = '\0';
.
Boolean value of null terminator
The null terminator
\0
has a boolean value offalse
which is equivalent to the integer0
!
Return length of string
Use
strlen(s)
,\n
is considered as a character.
String comparison
strcmp(s1, s2)
, it returns negative ifs1
is lexicographically less thans2
, positive if bigger, else both are equal.We should use
strncmp(s1, s2, n)
, because it safer, it will compare the firstn
characters if a null termination\0
is missing.
Assign string value in C
When we want to re-assign string value in C, we need to use
strcpy(s1, s2)
which assignss2
tos1
.We should use
strncpy(s1, s2, n)
, because it safer, it will only copy the firstn
characters if a null termination\0
is missing.
scanf()
- The syntax is
int scanf("%d", &a);
May have runtime crash
scanf()
reads until the first whitespace, so the input may be too large and causes the program to crash.The whitespace isn’t being read in.
fgets()
- The syntax is
char *fgets(char *str, int size, FILE *stream);
More reliable
fgets()
reads until the first newline character or the specifiedsize
(size-1
chars) is reached, whichever comes first. So we can control how large the input will be; any excess will simply be ignored.The
\n
is read in as one character.
Important
When we want to read in a string that should be null-terminated, but the string contains
\n
which prematurely terminates thefgets()
function, we can use the following code snippet to ensure it is still null-terminated.
puts()
- Print a string to the console with newline included
C IO
Read float
scanf("%f", &miles);
reads in a float number. The value it returns is the total number of successfully matched and assigned input items.
"%f"
is known as a format string,&miles
is known as a input list.
Print float
printf("That equals %9.3f km.\n", kms);
prints a floating-point number to the screen, formatted to occupy a minimal width of 9 characters (including the decimal point and any padding spaces if the number is shorter). The number will be displayed with 3 decimal places of precision.
"That equals %9.3f km.\n"
is known as a format string,kms
is known as print list.\n
is known as escape sequence to format the string.