Add 2 Strings In C

C also offers the option for developers to utilize pointers for string manipulation. Pointers serve as variables that hold the memory location of another variable. When applied to strings, pointers enable the passing of strings to functions, the manipulation of strings, and the return of strings from functions. To sum up, strings in C are a core data type utilized for representing textual information. They are structured as arrays of characters concluded by a null character, and can be altered using various functions. It is crucial to exercise caution when handling strings to prevent overwriting other memory data and to guarantee that strings are null-terminated. Pointers play a significant role in string manipulation and serve as a robust asset for string operations in C.

C Code

Example

#include <stdio.h>
#include <string.h>
int main() {
   char str1[100], str2[100], result[200];
   printf("Enter string 1: ");
   scanf("%s", str1);
   printf("Enter string 2: ");
   scanf("%s", str2);
   strcat(result, str1);
   strcat(result, str2);
   printf("Result: %s", result);
   return 0;
}

Output

Output

Enter string 1: Hello
Enter string 2: world
Result: Helloworld

The outcome of the preceding code will be reliant on the input provided by the user. Upon execution, the program will request the user to input two strings. Let's assume the user inputs "Hello" as the first string and "world" as the second string. Subsequently, the program will merge the two strings and save the combined result in the result array. Lastly, it will display the merged string using the printf function. It is important to note that in the output, "Hello" and "world" will be concatenated without a space in between, as a space character was not included in the result array. To insert a space between the two strings, the code could be adjusted to include a space character in the result array before concatenating the strings.

Explanation:

In this snippet, we initially define three arrays of characters: str1, str2, and result. Subsequently, we request input from the user for the initial and subsequent strings through the scanf function. Following that, we utilize the strcat function to merge the two strings within the result array. Since strcat appends the second string to the first, we invoke it twice to combine str1 and str2 within result. Ultimately, we exhibit the concatenated string by employing the printf function. It is important to note that this code assumes the user's input strings do not surpass the allocated size of the character arrays (str1 and str2). Should the input strings exceed 100 characters, there is a risk of a buffer overflow occurring. To mitigate this potential issue, one can either enlarge the array sizes or opt for a dynamic memory allocation mechanism such as malloc.

Input Required

This code uses input(). Please provide values below: