Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
497 views
in Computer by (26.0k points)

Explain with example by passing the pointers.

1 Answer

+1 vote
by (25.0k points)
selected by
 
Best answer

#include <iostream>
// function declaration void swap(int *, int *);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << “Before swap, value of a :” << a << endl;
cout << “Before swap, value of b:”<< b << endl;
/* calling a function to swap the values.*/
swap(&a, &b);
cout << “After swap, value of a << a << endl;
cout <<“After swap, value of b << b << endl;
}

// function definition to swap the values, void swap(int *x, int *y)
{
int temp;
temp = *x; // assign to temp from the value at address x
*x = *y; // put value at address y into x
*y = temp; // put value of temp into value at the address y
}

The output of the above program is:
Before swap, value of a :100 Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

In the above program, swap() function is declared with two arguments of type integer pointers. During the function call memory address of variable, ‘a’ and variable ‘b’ is passed as actual arguments, and formal arguments are pointer ‘x’ and pointer Y takes the address of ‘a’ and ‘b’ variables respectively. In the body of the swap function, the pointer operator is used to access the value at the location. Here the memory location of ‘a’ and ‘b’ are accessed by the pointers V and Y and produces the output as shown above.

Related questions

+1 vote
1 answer
+1 vote
1 answer
0 votes
2 answers
asked Jun 3, 2023 in C++ by kvdevika (106k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...