VOOZH about

URL: https://www.geeksforgeeks.org/cpp/c-style-string-in-c/

⇱ C Style String in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Style String in C++

Last Updated : 12 Feb, 2026

In C, a string is a character array terminated by a null character \0, making its size one more than the number of characters. C++ also supports this, and the compiler automatically adds \0 when initializing the array.

Initializing a String in C++:

1. char str[] = "Geeks";
2. char str[6] = "Geeks";
3. char str[] = {'G', 'e', 'e', 'k', 's', '\0'};
4. char str[6] = {'G', 'e', 'e', 'k', 's', '\0'};

Memory representation of a string "Geeks" in C++.
👁 Image

Commonly Used Functions for C-Style Strings

C-style strings rely on a number of functions defined in the <cstring> header. Let's explore three common functions:

1. strlen (String Length)

The strlen function calculates the length of a string by counting characters until it encounters \0.


Output
3
3

Explanation:

  • strlen ignores the null character while calculating the length.
  • If the null terminator is missing, strlen may traverse unintended memory, causing incorrect results or runtime errors.

2. strcmp (String Comparison)

The strcmp function compares two strings lexicographically:

  • Returns 0 if both strings are equal.
  • Returns a negative value if the first string is smaller.
  • Returns a positive value if the first string is greater.

Output
Greater

Explanation:

  • Characters are compared one by one based on their ASCII values.
  • Comparison stops as soon as a mismatch is found, or one string ends.

3. strcpy (String Copy)

The strcpy function copies the content of one string into another.


Output
gfg

Explanation:

  • strcpy copies characters, including the null terminator, from the source to the destination.
  • Ensure the destination array has enough space to hold the source string and the null terminator.
Comment
Article Tags:
Article Tags: