Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Character Arrays and String Basics | String Representation in C
C Strings

bookCharacter Arrays and String Basics

Deslize para mostrar o menu

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

main.c

copy
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

main.c

copy
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.

question mark

Why must a character array representing a string in C include a null-terminator?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 3
some-alt