HOME HTML EDITOR C JAVA PHP

C Strings:

In C, a String is not a built-in data type like in Java or Python. Instead, it is a one-dimensional array of characters that is terminated by a special character called the Null Character (\0).

1. The Null Terminator (\0)

The null character is essential because it tells functions like printf() where the string ends in memory. Without it, the program would continue reading garbage data from the RAM.

char greeting[] = "Hello";
// In memory, this takes 6 bytes: 'H' 'e' 'l' 'l' 'o' '\0'

2. Declaring and Initializing Strings

There are two primary ways to create a string in C:

3. The <string.h> Library

Since strings are arrays, you cannot compare or copy them using == or =. You must use the functions provided in the string.h header.

Function Purpose
strlen(str) Returns the length (excluding \0).
strcpy(dest, src) Copies src into dest.
strcat(dest, src) Appends src to the end of dest.
strcmp(s1, s2) Returns 0 if strings are identical.

4. String Input: scanf() vs fgets()

Reading strings from a user requires caution to avoid "Buffer Overflows."

char str[20];

// DANGEROUS: Stops at first space, might overflow buffer
scanf("%s", str);

// RECOMMENDED: Reads spaces and limits input to 20 characters
fgets(str, 20, stdin);

5. Common Pitfalls

6. Two-Dimensional Strings

To store a list of names, you use a 2D character array where each row is a string.

char students[3][10] = {"Amit", "Sita", "Rahul"};
printf("%s", students[0]); // Prints "Amit"
Pro Tip: For safer code, use strncpy() and strncat(). The "n" versions allow you to specify the maximum number of characters to copy, preventing accidental memory corruption!