Character Arrays and String Basics
Stryg for at vise menuen
When you work with strings in C, you are really working with arrays of characters rather than a specialized string type. Unlike higher-level languages such as Python, which provide built-in string objects with many features, C uses a much more direct approach: a string is just a sequence of characters stored in memory, ending with a special character to mark where the string finishes.
main.c
1234567#include <stdio.h> int main() { char greeting[] = "Hello"; printf("%s\n", greeting); return 0; }
In this example, the character array greeting is initialized with the string "Hello". Each character from the string—including the invisible null-terminator at the end—is stored in consecutive elements of the array. So, the array actually contains six elements: the letters 'H', 'e', 'l', 'l', 'o', and the null-terminator character \0. The array size must be large enough to hold all these characters, including the null-terminator, or the string will not be properly recognized by C's string functions.
main.c
123456// This example shows how to manually initialize a character array to represent a string in C. // Notice that we include the null-terminator '\0' at the end of the array. char word[6] = { 'H', 'e', 'l', 'l', 'o', '\0' }; // The array 'word' now holds the string "Hello" as a sequence of characters, // with the final '\0' marking the end of the string.
Here, you see each character placed into the array by hand, with the null-terminator \0 added at the end. The null-terminator is crucial because it signals the end of the string to C's string-handling functions. Without this character, functions that process the string would not know where the string ends and might continue reading into other memory, leading to unpredictable results or errors.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat