C

How To Concatenate Two Strings In C Using Pointers

In this tutorial, we are going to see how to concatenate two strings in C using pointers. A string is a sequence of characters, enclosed in quotes (""), used to represent a string terminated by a null character ‘\0’ in C. If we try to concatenate two strings using the + operator, it will fail. The following example shows you how to concatenate two strings in C using pointers.

100-multiple-choice-questions-in-c-programming100 Multiple Choice Questions In C Programming – Part 1This collection of 100 Multiple Choice Questions and Answers (MCQs) In C Programming : Quizzes & Practice Tests with Answer focuses on “C Programming”.  …Read More
 

How To Concatenate Two Strings In C Using Pointers
#include <stdio.h>
#include <string.h>
 
void main()
{
	char str1[256], str2[256], *p, *q;

	//ask the user to enter two strings
	printf("Enter the first string: ");
	gets(str1);
	printf("Enter the second string: ");
	gets(str2);

	//initialize pointers
	p = str1;
	q = str2;
	
	//move to the end of first string
	while(*p!='\0')
		p++;

	//copy the second string into first string
	while(*q!='\0')
	{
		*p=*q;
		q++;
		p++;
	}
	*p='\0';

	//display the result
	printf("After the concatenation: %s ",str1);
}

Output:

Enter the first string: Hello
Enter the second string: World
After the concatenation: HelloWorld

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *