CHARACTER ARRAYS [STRINGS]
Consider the following program,
#include <stdio.h> main() { static char name1[] = {'H','e','l','l','o'}; static char name2[] = "Hello"; printf("%s\n", name1); printf("%s\n", name2); } Sample Program Output Helloxghifghjkloqw30-=kl`' Hello
The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in name2[5], whilst name1 has not. This can often result in garbage characters being printed on the end. To insert a null at the end of the name1 array, the initialization can be changed to,
static char name1[] = {'H','e','l','l','o','\0'};
Consider the following program, which initialises the contents of the character based array word during the program, using the function strcpy, which necessitates using the include file string.h
#include <stdio.h> #include <string.h> main() { char word[20]; strcpy( word, "hi there." ); printf("%s\n", word ); } Sample Program Output hi there.