0
0
CHow-ToBeginner · 3 min read

How to Declare String in C: Syntax and Examples

In C, a string is declared as an array of characters using char type, ending with a null character \0. You can declare it like char name[20]; or initialize it with char name[] = "Hello";.
📐

Syntax

To declare a string in C, you use a character array. The array size defines the maximum length of the string including the null terminator \0. You can also initialize the string with text directly.

  • char name[size]; declares a string with a fixed size.
  • char name[] = "text"; declares and initializes a string with the given text.
  • The string must end with a \0 character to mark its end.
c
char name[20];
char greeting[] = "Hello";
💻

Example

This example shows how to declare, initialize, and print strings in C using printf. It demonstrates both fixed size and automatic sizing.

c
#include <stdio.h>

int main() {
    char name[20] = "Alice";  // fixed size array
    char greeting[] = "Hello, World!";  // size set automatically

    printf("Name: %s\n", name);
    printf("Greeting: %s\n", greeting);

    return 0;
}
Output
Name: Alice Greeting: Hello, World!
⚠️

Common Pitfalls

Common mistakes when declaring strings in C include:

  • Not leaving space for the null terminator \0, which ends the string.
  • Using uninitialized character arrays without setting values.
  • Trying to assign strings directly to arrays after declaration (which is not allowed).

Always initialize strings properly and ensure the array is large enough.

c
/* Wrong way: */
char str[5];
// str = "Hello";  // Error: cannot assign to array after declaration

/* Right way: */
char str[6] = "Hello";  // Includes space for '\0'
📊

Quick Reference

DeclarationDescription
char str[10];Declare a string with space for 9 characters + null terminator
char str[] = "Hi";Declare and initialize a string with automatic size
str[0] = 'H';Set individual characters in the string
printf("%s", str);Print the string to the console

Key Takeaways

Declare strings as character arrays with space for the null terminator '\0'.
Initialize strings at declaration or set characters individually before use.
Never assign a string directly to an array after declaration; use initialization instead.
Use %s in printf to display strings properly.
Always ensure the array size is enough to hold the string plus the null character.