Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Concatenating Strings | Common String Operations
Practice
Projects
Quizzes & Challenges
Вікторини
Challenges
/
C Strings

bookConcatenating Strings

Свайпніть щоб показати меню

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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 5

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 3. Розділ 5
some-alt