We already know about how to declare and initialize arrays. In particular, character arrays aren’t any exception! Let’s take an example of character array,
char name[] = {'c', 'h', 'r', 'i', 's', 't', 'o', 'p', 'h', 'e', 'r'};
Array ‘name’ contains 11 characters. While initializing ‘name’, list of 11 characters, each in single quotes and separated by comma with its adjacent character, put in a pair of curly braces. But this way of initialization is cumbersome at writing especially when long list of characters is to be typed in. Alternately, C standard gives shorthand notation to write initializer’s list. Below is an alternate way of writing the character array ‘name[]’,
char name[] = "christopher"; /* initializing 'name' */
But we, here, are a bit confused if name is a ‘String Literal’ or a character array containing 11 characters. Where’s the difference? Consider below given declaration and initialization,
char *name2 = "christopher"; /* is 'name2' a string literal? */
Both ‘name’ and ‘name2’ seems to be string literals. But difference between two is cleared by the context in which they are used. When ‘name’ has an initializer list, it’s called an array. Everywhere else, it’s a String literal. Therefore,
char name[] = "christopher";
is a character array. While
char *name2 = "christopher";
is a string literal. Actually, ‘name2’ is a pointer-to-char_string, points to string “christopher” wherever is stored in memory.
/* * diff_char_arr_str.c -- program shows difference between character array * and string Literal */ #include <stdio.h> #include <string.h> int main(void) { char name[] = "christopher"; /* character array */ char *name2 = "christopher"; /* string literal */ printf("name \"%s\" is an array and name2 \"%s\" is a string literal.\n" , name, name2); return 0; }
Output as:
name “christopher” is an array and name2 “christopher” is a string literal.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Practice BCA MCQs
- Apply for C Internship
- Watch Advanced C Programming Videos