Answer: Let’s, first, consider following declarations,
#define STR_LIT "I'm string literal declared using #define" char *str_lit = "I'm string literal declared through pointer-to-char"; char char_arr[5] = {'a','b','c','d','e'}; /* character array */
Let’s, now, embed them into a program below,
/* * diff_chararr_strlit.c -- program differentiates char array and string * literal */ #include <stdio.h> #define STR_LIT "I'm string literal declared using #define" int main(void) { char *str_lit = "I'm string literal declared through pointer-to-char"; char char_arr[5] = {'a','b','c','d','e'}; /* character array */ puts("\n*****Program differentiates character array and " "string literal*****\n"); puts(STR_LIT); /* add. of string literal passed to puts */ puts(str_lit); puts("\n"); puts("Let's, now, try to access character array as character string..." "\n"); puts(char_arr); puts("\n"); return 0; }
Output of above program when run on Linux Machine is as below,
*****Program differentiates character array and string literal***** I'm string literal declared using #define I'm string literal declared through pointer-to-char Let's, now, try to access character array as character string... abcde
So, what here you observed when accessed character array ‘char_arr as character string by passing its address to puts? Output contains all characters from the ‘char_arr’ with some extra unspecified characters appended in the end. How’s this? Actually, puts prints characters until it finds NULL terminator. Since, ‘char_arr’ wasn’t containing one therefore puts continued after the end of ‘char_arr’ until it found one. Then how to access character arrays? It’s easy, use loops with counter explicitly specifying no. of characters in character array. For example, to access ‘char_arr’,
for (i = 0; i < 5; i++) putc(char_arr[i]); /* or printf("%c", char_arr[i]) */
String literals whether declared using #define statements or using pointer-to-char contain NULL bytes. In initialization
char *str_lit = "I'm string literal declared through pointer-to-char";
‘str_lit’ is a pointer to string “I’m string literal declared through pointer-to-char” wherever stored in memory. In string literals or string constants, there’s no visible NULL terminator. Compiler appends it with NULL terminator while compiling the program.
There’s one more basic difference between character array and string literal and that is string literals, like symbolic constants, are constant strings while character arrays aren’t.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Apply for C Internship
- Check Computer Science Books
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship