Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Concatenating Strings | Common String Operations
C Strings

bookConcatenating Strings

Deslize para mostrar o menu

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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 5

Pergunte à IA

expand

Pergunte à IA

ChatGPT

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

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