A string in C is an array of characters ending with a null character (\0).
Unlike some other languages, C does not have a built-in string type; instead, strings are implemented using character arrays.
char str1[10] = "Hello"; printf("%s\n", str1);
● The array str1 has a xed size of 10, but only 5 characters are used (Hello) plus the null terminator.
● The remaining elements remain uninitialized.
char *str2 = "World";
printf("%s\n", str2);
A pointer is a variable that stores the memory address of another variable.
Instead of holding an actual value, a pointer holds the location where the value is stored.
str2 is a pointer to a string literal stored in read-only memory.
Modifying it can lead to undened behavior.
char str3[20];
The array str3 has space for 20 characters but is uninitialized, meaning it may contain garbage values until explicitly assigned.
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
Limitation: Stops at whitespace (e.g., "Palawan Cherry" → only "Palawan" is stored).
char name[50];
gets(name);
printf("Your input: %s\n", name);
Danger: No buffer limit, making it vulnerable to buffer overflow.
Note: gets() is deprecated and should not be used.
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
Advantage: Reads full lines, including spaces.
Prevents buffer overflow by limiting input size.
Best practice for handling strings safely in C.
✅ Use fgets() instead of gets() to avoid overflow.
✅ Ensure enough space when using strcpy() or strcat().
✅ Use strcmp() (not ==) for string comparison.
✅ For dynamic strings, use malloc() and free() to manage memory.
✅ Always initialize strings to avoid garbage values.
Counts characters before \0 (null terminator).
Output: Length: 5
Copies a string but does NOT check size.
Risk: Buffer overflow if destination is too small.
Output: Copy this
Appends str2 to str1 (ensure enough space).
Output: Hello World
Returns:
0 if equal
Negative if first is smaller
Positive if first is larger
Output: A negative value (abc < xyz)