The Program in C to concatenate two strings using pointers is given below:
#include <stdio.h>
void string_concat(char *dest, char *src) {
while (*dest != '\0') {
dest++;
}
while (*src != '\0') {
*dest = *src;
src++;
dest++;
}
*dest = '\0';
}
int main() {
char string1[100], string2[100];
printf("Enter the first string: ");
fgets(string1, 100, stdin);
printf("Enter the second string: ");
fgets(string2, 100, stdin);
string_concat(string1, string2);
printf("The concatenated string is: %s\n", string1);
return 0;
}
Output:
Enter the first string: be empathetic
Enter the second string: be kind
The concatenated string is: be empathetic
be kind
Pro-Tips💡
In this program, the string_concat
function takes two pointers as arguments, one for the destination string and one for the source string.
The function uses the pointers to iterate through the destination string until it finds the null character ‘\0’ and then it starts to iterate through the source string, copying each character to the destination string by using the dereference operator *
to access the value pointed to by the pointers.
It copies each character until the null character ‘\0’ is found. In the main function, the user is prompted to enter two strings which are read by fgets
and stored in the variables string1
and string2
.
These two strings are passed to the string_concat
function as arguments. After the concatenation is done, the string1
variable is printed to the console which now contains the concatenated string.
This code uses pointers to access the memory addresses of the characters in the destination and source strings, and to copy the characters from the source string to the destination string
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.