Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære String Initialization Methods | String Initialization and Input/Output
/
C Strings

bookString Initialization Methods

Stryg for at vise menuen

When working with strings in C, you have several ways to initialize them, each with its own syntax and behavior. The most common methods are using string literals, character arrays with explicit characters, and pointers to string literals. Understanding the differences between these approaches is essential for writing safe and efficient C programs.

main.c

main.c

copy
1234567891011121314
#include <stdio.h> int main() { // Initializing a string using a string literal char str1[] = "Hello"; // Initializing a string as a character array with explicit characters char str2[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; printf("str1: %s\n", str1); printf("str2: %s\n", str2); return 0; }

Both str1 and str2 represent the string "Hello", but they are initialized differently. When you use a string literal, such as in char str1[] = "Hello";, the compiler automatically adds the null terminator and allocates enough space for all the characters including \0. In contrast, initializing with explicit characters, as in char str2[] = { 'H', 'e', 'l', 'l', 'o', '\0' };, requires you to manually include the null terminator. In both cases, the string data is stored in a modifiable character array, meaning you can change individual characters in the string after initialization. The key difference lies in the syntax and the requirement to manage the null terminator yourself when using explicit character arrays.

main.c

main.c

copy
12345678910
#include <stdio.h> int main() { // Pointer-based string initialization const char *str = "Hello"; printf("str: %s\n", str); return 0; }

When you initialize a string with a pointer to a string literal, such as const char *str = "Hello";, the pointer str points to a read-only section of memory where the string literal is stored. This means you cannot safely modify the contents of the string through this pointer. Attempting to do so can lead to undefined behavior, including program crashes. The benefit of this approach is that it uses less stack memory, since only a pointer is stored, not the entire array. However, the risk is that string literals are typically stored in read-only memory, so you must avoid writing to them. This method is useful for read-only string data, but not suitable if you need to change the string.

question mark

Which string initialization method in C allows for modification of the string contents?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 2. Kapitel 1
some-alt