Introduction to Programming and C++

Contents Previous Topic Next Topic

In C++, Java, and C#, there is a class which represents strings, either string or String. These objects have member functions which can deal with these objects.

In C, strings are much more primitive. A string is simply an array of characters which is terminated with the null character '\0' (i.e., character 0, not the digit 0).

For example, in Program 1, we have a pointer to a char which is assigned the address of the string "Hello". The compiler allocates six bytes for this string, the sixth being the '\0' character which designates the end of the string. When we print the string using %s, printf continues to print characters until it finds the '\0' character.

Program 1. Hello World!

#include <stdio.h>

int main() {
	char * str = "Hello";

	printf( "The result of %s\n", str );

	return 0;
}

Program 2 demonstrates this more clearly:

Program 2. Hello World!

#include <stdio.h>

int main() {
	char * str = "Hello";

	printf( "The result of %s\n", str );

	int i;

	for ( int i = 0; i < 6; ++i ) {
		printf( "Character #%d is '%c' which equals %d\n", i, str[i], (int) str[i] );
	}

	return 0;
}

Note that we are explicitly printing the quotes in the string statement. If you just printed the characters with %c, the quotes would not appear.


Contents Previous Topic Top Next Topic