Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Concatenating Strings | Common String Operations
Practice
Projects
Quizzes & Challenges
Quizze
Challenges
/
C Strings

bookConcatenating Strings

Swipe um das Menü anzuzeigen

When working with strings in C, you often need to combine, or concatenate, two or more strings into one. This process is called string concatenation. C provides standard library functions for this purpose, with strcat and strncat being the most commonly used. These functions allow you to append the contents of one string to the end of another, but you must manage memory carefully to avoid errors.

main.c

main.c

copy
123456789101112
#include <stdio.h> #include <string.h> int main() { char dest[20] = "Hello, "; char src[] = "world!"; strcat(dest, src); printf("%s\n", dest); // Output: Hello, world! return 0; }

In this code, you see how strcat joins the content of src to the end of dest. It is crucial to ensure that the destination array, dest, is large enough to hold both the original string and the appended string, plus the null terminator. If the buffer is too small, you risk overwriting memory, which can lead to bugs or crashes.

main.c

main.c

copy
123456789101112
#include <stdio.h> #include <string.h> int main() { char dest[12] = "Good "; char src[] = "morning sunshine!"; strncat(dest, src, 5); printf("%s\n", dest); // Output: Good morni return 0; }

Using strncat lets you specify the maximum number of characters to append from the source string, making it safer than strcat. This approach helps prevent buffer overflows by limiting how much data is copied, even if the source string is longer than expected. By controlling the number of characters, you reduce the risk of writing past the end of the destination array and make your code more robust.

question mark

What must you check before concatenating strings in C?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 5

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 3. Kapitel 5
some-alt