In C, strings are sequences of characters terminated by a null character (‘\0’). They are typically represented as arrays of characters. There are two common ways to declare and initialize strings in C: using character arrays and using pointers to string literals.
1. Character Arrays:
You can declare strings using character arrays. The array size should be large enough to accommodate the string characters along with the null terminator (‘\0’).
char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
In this declaration:
- char specifies the data type of the array elements (characters).
- greeting is the name of the array.
- [6] indicates the size of the array, including space for the null terminator.
- {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’} initializes the array with the string “Hello”, with the null terminator explicitly included.
2. Pointers to String Literals:
You can also declare strings using pointers to string literals. String literals are sequences of characters enclosed in double quotes.
char *greeting = “Hello”;
In this declaration:
- char * declares a pointer to a character, which points to the first character of the string.
- greeting is the name of the pointer variable.
- “Hello” is the string literal, which is stored in read-only memory.
- There’s no need to specify the size of the array because the compiler automatically calculates it based on the length of the string literal.
Initialization:
String initialization can also be done using string literals, enclosed in double quotes:
char greeting[] = “Hello”;
In this case, the compiler calculates the size of the array automatically, including space for the null terminator (‘\0’).
Null Terminator:
In C, strings are terminated by a null character (‘\0’). This character signifies the end of the string and is added implicitly when using string literals or explicitly when initializing character arrays.
Example:
Here’s an example demonstrating string declaration and initialization:
#include <stdio.h>
int main() {
char greeting[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
char *greetingPtr = “Hello”;
printf(“Using character array: %s\n”, greeting);
printf(“Using pointer to string literal: %s\n”, greetingPtr);
return 0;
}
Output:
Using character array: Hello
Using pointer to string literal: Hello
Both methods result in the same string “Hello”. However, the second method uses a pointer to refer to the string literal.