C strings
Created By: chatGPT
In C programming, a string is essentially an array of characters terminated by a null character (
\0
). This means that the last character in the string will always be \0
to signify the end of the string. When dealing with C strings, it's important to remember that string operations must consider this null termination.#include <stdio.h>
int main() {
char str[20] = "Hello, World!";
printf("%s\n", str);
return 0;
}
You can declare a C string using either a character array or a pointer to character. The following example shows both methods of declaring a C string.
char str1[20] = "Hello";
char *str2 = "World";
To copy, concatenate, or manipulate C strings, you can use the functions defined in the
string.h
library, such as strcpy
, strcat
, and strlen
. Make sure to include the string.h
library at the beginning of your program.#include <string.h>
void demoStringFunctions() {
char src[20] = "Hello";
char dest[20];
strcpy(dest, src);
strcat(dest, " World");
printf("%s\n", dest);
}
An important point to remember is about memory allocation. When a string is declared as a character array, sufficient memory must be allocated to store all characters including the null terminator. Failure to provide enough space can lead to buffer overflow, which is a common security vulnerability in C programming.
char str[10]; // This can store 9 characters plus the null terminator
strcpy(str, "Hello"); // Unsafe if the source string length exceeds 9
When working with strings, you can also compare them using the
strcmp
function from the string.h
library. This function compares two strings lexicographically and returns an integer value based on the comparison.#include <string.h>
int main() {
char str1[] = "ABC";
char str2[] = "ABD";
int result = strcmp(str1, str2);
if(result < 0) {
printf("'%s' is less than '%s'\n", str1, str2);
}
return 0;
}