The most common type of array in C is the array of characters.
Let’s look at an example where we input multiple lines of text, reverse it and print it.
#include <stdio.h> #define MAX_LEN 80 int get_line(char [], int); void reverse(char [], char [], int); int main() { int len; char line[MAX_LEN]; char rev_line[MAX_LEN]; while ((len = get_line(line, MAX_LEN)) > 0) { reverse(line, rev_line, len); printf("Reverse of %s is %s.\n", line, rev_line); } return 0; } int get_line(char line[], int max_len) { int c, i; for(i = 0; i < max_len - 1 && (c = getchar()) != EOF && c != '\n'; i++) { line[i] = c; } line[i] = '\0'; return i; } void reverse(char source[], char dest[], int length) { int i; for (i = 0; i < length; i++) { dest[i] = source[length - i - 1]; } dest[i] = '\0'; }
The function get_line reads a line of text and stores it in the array line. We also pass max_len, to make sure we don’t exceed the array length and cause overflow. This function returns the number of characters in a line of text.
getline inserts ‘\0’ (null character) at the end of the array it is creating, to mark the end of the string of characters. This is a convention used in C for strings. So, a string constant like “hello” is stored as an array of characters containing the string and terminated by a null character(‘\0’) to mark the end.
The %s format specifier in printf expects the corresponding argument to be a string represented in this form.
The reverse function takes a source, a dest and the length of the source string. It then copies over the characters from source starting from the last character, to dest. It finally copies the null character(‘\0’) to make it a string.