Print Char Array in C

After we have introduced how to print in C, we will introduce multiple methods about how to print a char array in C.
Use the for
Loop to Print Char Array in C
The for
loop is the most obvious solution if we want to print array elements separately and format the output with more details. A critical prerequisite for this method is that we should know the array length in advance.
Note that we can use other iteration methods like the while
loop, but then we should know the value at which the iteration should stop; otherwise, the iteration would go out of bounds throwing the segmentation fault.
In the following example, we demonstrate the for
loop method and iterate precisely 6 times over the array of six characters.
#include <stdio.h>
#include <stdlib.h>
#define STR(num) #num
int main(void) {
char arr1[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
printf(STR(arr1)": ");
for (int i = 0; i < 6; ++i) {
printf("%c, ", arr1[i]);
}
printf("\b\b\n");
exit(EXIT_SUCCESS);
}
Output:
arr1: a, b, c, d, e, f
Use printf
With %s
Specifier to Print Char Array in C
The printf
function is a powerful function for formatted output. It can manipulate input variables with type specifiers and process variables correspondingly.
Namely, the char
array internally has the same structure as the C-style string, except that the C-style string characters always end with \0
byte to denote the ending point. If we add the null byte at the end of our char
array, we can print the whole array with a single-line printf
call.
If the terminating null byte is not specified and printf
is called with this method program may try to access memory regions that will most likely result in segmentation error.
#include <stdio.h>
#include <stdlib.h>
#define STR(num) #num
int main(void) {
char arr1[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
char arr2[] = { 't', 'r', 'n', 'm', 'b', 'v', '\0' };
printf("%s\n", arr1);
printf("%s\n", arr2);
exit(EXIT_SUCCESS);
}
Output:
abcdeftrnmbv
trnmbv
As you can see, when we print the arr1
that doesn’t have the null terminator, we will get more characters until the iteration reaches one null terminator - \0
.
Another method to specialize the printf
function is to pass the number of characters in the string inside the %s
specifier. One way of doing this is to statically hard-code the length of the string with an integer between the symbols %
and s
, or it can be replaced with *
symbol to take another integer argument from the printf
parameters. Note that both methods include .
character before the number or asterisk in the specifier.
#include <stdio.h>
#include <stdlib.h>
#define STR(num) #num
int main(void) {
char arr1[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
char arr2[] = { 't', 'r', 'n', 'm', 'b', 'v', '\0' };
printf("%.6s\n", arr1);
printf("%.*s\n", (int)sizeof arr1, arr2);
exit(EXIT_SUCCESS);
}
Output:
abcdef
trnmbv