Skip to content
StudyFame

Strings in C

Names, city names, passwords, messages: most data in real programs is text. C has no special "string" data type like Python or Java. Instead, C stores text as an array of characters with a special ending mark.

In this lesson you will learn what a string is in C, how to declare and initialize one, and why the hidden '\0' character is so important. Every string topic after this depends on it.

What You Will Learn

  • What a string is in C.
  • What the null character '\0' is and why it is needed.
  • Different ways to declare and initialize a string.
  • How a string is stored in memory.
  • The difference between 'A' and "A".
  • How to print a string with %s.

What is a String in C?

Exam definition: A string in C is a one-dimensional array of characters terminated by the null character '\0'. The null character marks the end of the string.

Memory trick: '\0' is the full stop of a C string. Without the full stop, C keeps reading into memory and doesn't know where your sentence ends.

  • '\0' is a character whose ASCII value is 0. It is not the digit '0' (ASCII 48).
  • Text in double quotes, like "Hello", is a string literal. C adds the '\0' at the end for you.
  • So "Hello" has 5 visible letters but needs 6 bytes.

Syntax to Declare and Initialize a String

char name[size];                                 /* declaration */

char city[10] = "Delhi";                         /* string literal: '\0' added */
char city[]   = "Delhi";                         /* size taken as 6 */
char city[6]  = {'D', 'e', 'l', 'h', 'i', '\0'}; /* character by character */
char city[10] = {0};                             /* empty string, all '\0' */
  • Always keep one extra space for '\0': size ≥ number of letters + 1.
  • When you write characters one by one, you must add '\0' yourself.
  • Print a whole string with printf("%s", city); and one character with printf("%c", city[0]);.

How a String is Stored in Memory

char city[10] = "Delhi";

Index :   0    1    2    3    4    5    6    7    8    9
Value :  'D'  'e'  'l'  'h'  'i' '\0' '\0' '\0' '\0' '\0'
         |------ string -----|  end   unused (filled with 0)
  • The array size is 10 bytes, but the string length is 5.
  • %s prints characters from index 0 and stops at the first '\0'.

Example 1: Declare, Initialize and Print Strings

#include <stdio.h>

int main(void)
{
    char city[10] = "Delhi";
    char lang[] = {'C', '\0'};
    char course[] = "BTech";

    printf("City     : %s\n", city);
    printf("Language : %s\n", lang);
    printf("First letter of course: %c\n", course[0]);

    course[0] = 'M';                    /* change one character */
    printf("Changed  : %s\n", course);

    printf("Bytes used by course: %zu\n", sizeof(course));

    return 0;
}

Output

City     : Delhi
Language : C
First letter of course: B
Changed  : MTech
Bytes used by course: 6

Code Explanation

  1. char city[10] = "Delhi"; stores 5 letters plus '\0'; the other 4 places become '\0' too.
  2. char lang[] = {'C', '\0'}; builds a string letter by letter. The '\0' makes it a proper string.
  3. %s takes the array name and prints up to the null character. %c prints one character.
  4. course[0] = 'M'; changes one element of the array, so "BTech" becomes "MTech".
  5. sizeof(course) is 6: five letters plus the hidden '\0'.

Character vs String: 'A' vs "A"

Point'A' (character)"A" (string)
QuotesSingleDouble
Typechar (really an int value 65)Array of char
Memory1 byte2 bytes: 'A' and '\0'
Format specifier%c%s

Example 2: Walk Through a String Until '\0'

Because every string ends with '\0', a loop can find the end without knowing the length. This loop is the base of most string programs.

#include <stdio.h>

int main(void)
{
    char word[] = "Program";
    int i, vowels = 0;

    printf("Letters:");
    for (i = 0; word[i] != '\0'; i++)       /* stop at the full stop */
    {
        printf(" %c", word[i]);
        if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' ||
            word[i] == 'o' || word[i] == 'u')
            vowels++;
    }
    printf("\n");

    printf("Length : %d\n", i);
    printf("Vowels : %d\n", vowels);
    printf("ASCII of '\\0' is %d\n", '\0');

    return 0;
}

Output

Letters: P r o g r a m
Length : 7
Vowels : 2
ASCII of '\0' is 0

When the loop stops, i is the index of '\0', which equals the length of the string. See also check whether a character is a vowel or consonant.

Important Points to Remember

  • A C string is a char array ending with '\0'.
  • String literals in double quotes get '\0' automatically.
  • Array size must be at least length + 1.
  • %s prints until the first '\0'; %c prints one character.
  • Loop over a string with for (i = 0; s[i] != '\0'; i++).
  • '\0' (value 0) is different from '0' (value 48).

Common Mistakes Beginners Make

MistakeWhat happensFix
char s[5] = "Hello";No room for '\0': printing shows garbagechar s[6] or char s[]
Char list without '\0'%s reads past the endAdd '\0' as the last element
s = "Pune"; after declarationCompile error: can't assign arraysstrcpy(s, "Pune");
char c = "A";Error/warning: string into a charchar c = 'A';
Using %c for a whole stringWrong output or crashUse %s

Strings in C Practice Questions

  1. Define a string in C.
  2. How many bytes does "India" need?
  3. What is the difference between '\0' and '0'?
  4. Why can't we write name = "Ravi"; after declaring char name[20];?
  5. What does printf("%s", s) do when it reaches '\0'?
Show answers
  1. A one-dimensional character array terminated by the null character '\0'.
  2. 6 bytes (5 letters + '\0').
  3. '\0' is the null character with ASCII value 0; '0' is the digit zero with ASCII value 48.
  4. An array name cannot be assigned. Use strcpy(name, "Ravi");.
  5. It stops printing.

Coding Exercise

Store "StudyFame" in a string. Using a loop that stops at '\0', count the capital letters and print the string with each character on the same line separated by -.

Show solution
#include <stdio.h>

int main(void)
{
    char s[] = "StudyFame";
    int i, caps = 0;

    for (i = 0; s[i] != '\0'; i++)
    {
        if (s[i] >= 'A' && s[i] <= 'Z')
            caps++;
        printf("%c", s[i]);
        if (s[i + 1] != '\0')
            printf("-");
    }
    printf("\nCapital letters: %d\n", caps);
    return 0;
}
S-t-u-d-y-F-a-m-e
Capital letters: 2

Quick Quiz: Strings in C (MCQ)

  1. A string in C ends with:

    A) '\n'   B) '0'   C) '\0'   D) EOF

  2. sizeof("Hi") is:

    A) 2   B) 3   C) 1   D) 4

  3. Format specifier for a string:

    A) %c   B) %d   C) %s   D) %str

  4. Which declaration is wrong?

    A) char s[] = "OK";   B) char s[3] = "OK";   C) char s[10];   D) char s = "OK";

  5. ASCII value of the null character:

    A) 48   B) 0   C) 32   D) 255

Show answers
  1. C: '\0'.
  2. B: 3 (two letters + '\0').
  3. C: %s.
  4. D: a string can't go into a single char.
  5. B: 0.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Stringchar array ending with '\0'
'\0'Null character, ASCII 0
Size neededlength + 1
Print string%s (stops at '\0')
'A' vs "A"1 byte vs 2 bytes
Assign laterUse strcpy, not =

Frequently asked questions

What is a string in C?
A character array terminated by the null character '\0'.
Why is the null character needed?
It tells functions like printf and strlen where the string ends.
Does C have a string data type?
No. C uses char arrays (or char pointers) for strings.

Remember

  • '\0' = the full stop of a string.
  • Always count +1 for it.

Next Topic

Next lesson: String Input and Output in C. You will read a string from the keyboard, including names with spaces.