Strings: introduction

Now that we have introduced the char type, it's time to talk about strings. We've been using strings in "double quotes" since our very first "Hello, world!" example, but we never talked about them; so it's time to do it now.

Strings are char arrays terminated by a zero character

There is no special "string" type in C. From the C language point of view, a string is just an array of characters:

char s[10];  /* array of 10 characters */

You could remember than when we were talking about arrays and passing arrays to functions, I kept saying that an array, when passed to a function, is "decayed" to a pointer to its 0-th element and there is no way for a function to know how many elements are there in that array, so we normally pass the length of the array separately as a parameter.

With strings, there is an important agreement that most string functions respect: a character with code 0 means the end of the string. That means that to store a string of 5 characters, e.g. "hello", you will need 6 char elements: 'h', 'e', 'l', 'l', 'o', and 0. It is actually possible to initialize your array like this:

char s[6] = "hello";

and even easier: when you initialize your char array with a string, you can omit the size, and it will be calculated automatically:

char s[] = "hello";
|     index |   0   1   2   3   4   5  | 
| character |  'h' 'e' 'l' 'l' 'o' NUL |
|      code |  104 101 108 108 111  0  |

This convention allows you to pass strings to functions like printf without explicitly passing the length as a parameter. When you call printf("hello"), the printf function iterates over the char array given, until it sees a zero character (0, not '0' = 48), and stops.

Now, as a quick exercise, implement a function that prints a string using putchar: if you have char c, you can call putchar(c) to print it. Note that since a string is a char array, we can pass it to the function as a pointer to a char, that is, char *:

#include <stdio.h>

void print_string(char *str) {
	/* TODO: your code here */
	/* keep iterating over characters in str and call putchar for each of them,
     until you see 0 */
}

int main() {
	print_string("hello\n");
	print_string("world\n");
	print_string("\n");
	print_string("");
	return 0;
}

Note that in C, zero means "false", so loops like the one you need to write often look like this:

for (i = 0; str[i]; ++i) {  /* the condition means: str[i] != 0 */
	...
}

On the next page we'll learn about even more idiomatic way to iterate over a string!

© Alexander Fenster (contact)