C Declaring Strings

Beginner
6 min read
Updated: Nov 2026
1 example

What Is Declaring Strings?

You usually declare strings as char arrays initialized from a literal, or as char * pointing at a literal. Prefer arrays when you will modify the text; use pointers to literals only for read-only text.

Remember
char name[] = "Ada";     /* mutable array copy */
char *label = "Ada";     /* pointer to literal — do not write */
char big[32] = "Ada";    /* array with spare room */

Cheat Sheet

TopicDetail
Array + literalchar s[] = "hi"; — size inferred
Fixed bufferchar s[N] = "hi"; — N includes \0
Pointerchar *p = "hi"; — read-only literal
Emptychar s[1] = ""; or s[0] = '\0';

C Examples

Compile with gcc file.c -std=c11 -Wall -o out. Next: String Input and Output.

Example 1

C
#include <stdio.h>
#include <string.h>

int main(void) {
    char city[] = "Paris";
    char buffer[16] = "Paris";

    printf("city: %s (sizeof %zu)\n", city, sizeof city);
    strcpy(buffer, "Lyon");
    printf("buffer: %s\n", buffer);
    return 0;
}

How It Works

  1. city[] sizes itself to the literal including \0 (6 bytes).
  2. buffer has spare capacity for longer text.
  3. strcpy copies "Lyon" including the terminator into buffer.

Edge Cases & Pitfalls

write

Writing through char * to a literal

Modifying "text" via a pointer is undefined behavior.

room

Too-small array

char s[3] = "Hi!"; does not fit — need space for \0.

Key Takeaways

  • Mutable: use a char array (or malloc).
  • Read-only: a pointer to a literal is fine for display.
  • Capacity: array size must fit text + \0.

One line: Declare a mutable array for editable text; pointers to literals are read-only.

Frequently Asked Questions

The literal includes two letters plus the hidden \0, so three bytes.
strdup (POSIX/C23) allocates a heap copy. Learn arrays and strcpy first, then dynamic allocation.
String Input and Output covers printf, puts, and safe reading with fgets.

Next: String Input and Output

Continue the C strings track.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful