How to Initialize String in C: Syntax and Examples
In C, you can initialize a string by declaring a character array with double quotes like
char str[] = "Hello"; or by using a pointer to a string literal like char *str = "Hello";. The first creates a modifiable array, while the second points to a read-only string.Syntax
There are two common ways to initialize strings in C:
- Character array:
char str[] = "text";creates an array with space for the string and a null terminator. - Pointer to string literal:
char *str = "text";points to a fixed string stored in read-only memory.
The null terminator \0 marks the end of the string in both cases.
c
char str1[] = "Hello"; char *str2 = "World";
Example
This example shows how to initialize strings using both methods and print them.
c
#include <stdio.h> int main() { char str1[] = "Hello"; // modifiable array char *str2 = "World"; // pointer to string literal printf("str1: %s\n", str1); printf("str2: %s\n", str2); // Modifying str1 is allowed str1[0] = 'h'; printf("Modified str1: %s\n", str1); // Modifying str2 is undefined behavior and should be avoided return 0; }
Output
str1: Hello
str2: World
Modified str1: hello
Common Pitfalls
Common mistakes when initializing strings in C include:
- Trying to modify a string literal through a pointer, which causes undefined behavior.
- Not leaving space for the null terminator when declaring character arrays.
- Using uninitialized character arrays without setting values.
Always ensure arrays have enough space and avoid changing string literals.
c
#include <stdio.h> int main() { // Wrong: modifying string literal causes crash or undefined behavior char *str = "Hello"; // str[0] = 'h'; // Do NOT do this! // Right: use character array to modify string char str2[] = "Hello"; str2[0] = 'h'; printf("%s\n", str2); return 0; }
Output
hello
Quick Reference
| Method | Syntax | Modifiable | Notes |
|---|---|---|---|
| Character array | char str[] = "text"; | Yes | Array stores string with null terminator |
| Pointer to literal | char *str = "text"; | No | Points to read-only memory, do not modify |
Key Takeaways
Use character arrays to create modifiable strings with space for the null terminator.
Use pointers to string literals only for read-only strings and avoid modifying them.
Always ensure strings end with a null terminator '\0' to mark their end.
Modifying string literals causes undefined behavior and should be avoided.
Initializing strings properly prevents common bugs and crashes in C programs.