Передача указателей в функции означает объявление параметра функции в качестве указателя, при вызове функции передается адрес переменной, и этот адрес будет храниться параметром, который объявлен как указатель.
Чтобы изменить значение любой переменной в функции, мы должны передать адрес этой переменной в функцию.
Пример:
С++
// C++ program to change value of x
// by passing an argument to a function
// without a pointer
#include <iostream>
using
namespace
std;
void
fun(
int
x) { x = 5; }
// Driver code
int
main()
{
int
x = 9;
cout <<
"value of x before calling fun: "
<< x << endl;
fun(x);
cout <<
"value of x after calling fun: "
<< x << endl;
return
0;
}
Выход
value of x before calling fun: 9 value of x after calling fun: 9
В приведенном выше коде адрес значения элемента x не зависит от изменения значения в функции, поскольку адреса обеих переменных разные.
Другой случай может быть, когда мы хотим изменить его значение в функции. В таких случаях мы используем указатели.
Пример:
С++
// C++ program to change values of x
// by passing an argument to a function
// with a pointer
#include <iostream>
using
namespace
std;
void
fun(
int
* ptr) { *ptr = 5; }
// Driver code
int
main()
{
int
x = 9;
cout <<
"value of x before calling fun: "
<< x << endl;
fun(&x);
cout <<
"value of x after calling fun: "
<< x << endl;
return
0;
}
Выход
value of x before calling fun: 9 value of x after calling fun: 5
В приведенном выше коде фактическое значение x передается, поскольку мы передаем адрес, который хранится в указателе ptr.
Пример:
С++
// C++ program to swap two values
// without passing pointer to
// swap function.
#include <iostream>
using
namespace
std;
void
swap(
int
x,
int
y)
{
int
temp = x;
x = y;
y = temp;
}
// Driver code
int
main()
{
int
a = 2, b = 5;
cout <<
"values of a and b before swapping: "
<< a
<<
" "
<< b << endl;
swap(a, b);
cout <<
"values of a and b after swapping: "
<< a <<
" "
<< b << endl;
return
0;
}
Выход
values of a and b before swapping: 2 5 values of a and b after swapping: 2 5
Пример:
С++
// C++ program to swap two values
// without passing pointer to
// swap function.
#include <iostream>
using
namespace
std;
void
swap(
int
* x,
int
* y)
{
int
temp = *x;
*x = *y;
*y = temp;
}
// Driver code
int
main()
{
int
a = 2, b = 5;
cout <<
"values of a and b before swapping: "
<< a
<<
" "
<< b << endl;
swap(&a, &b);
// passing address of a and b
cout <<
"values of a and b after swapping: "
<< a <<
" "
<< b << endl;
return
0;
}
Выход
values of a and b before swapping: 2 5 values of a and b after swapping: 5 2
Указатель функции в массиве
Массив — это тип структуры данных с непрерывными блоками памяти, которые могут хранить данные с аналогичным типом данных. Кроме того, имя массива представляет его первый адрес блока памяти. Итак, мы можем использовать это свойство для доступа к элементам массива.
Чтобы узнать больше об этом, обратитесь к статье — Массив в C++.
Пример:
С++
// C++ program to display element of
// array by passing argument to a
// function with pointer.
#include <iostream>
using
namespace
std;
void
display(
int
* ptr,
int
n)
{
for
(
int
i = 0; i < n; ++i) {
cout << *(ptr + i) <<
" "
;
}
}
int
main()
{
int
arr[] = { 1, 2, 3, 4, 5 };
int
n =
sizeof
(arr) /
sizeof
(
int
);
// ptr will store the address of first block of array
int
* ptr = arr;
// passing argument to a function as pointer.
display(ptr, n);
return
0;
}
Выход
1 2 3 4 5