函数指针和传递指针之间的区别

Difference between Function pointer and passing pointers

本文关键字:指针 区别 之间 函数      更新时间:2023-10-16

我有这些代码...

#include <iostream>
using namespace std;

int * Function (int  a, int  b);

int main() 
{
int a = 2;
int b = 7;
int * x = &a;
int * y = &b;
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
Function (a , b);
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
Function (a ,  b);
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
system ("PAUSE");
return 0;
}
int * Function (int  a, int  b)
{
int pom; 
pom =  a;
a = b; 
b = pom;
}

这是函数指针,不更改变量。我不知道为什么,以及功能指针到底是什么意思。为什么这种指针有用?

#include <iostream>
using namespace std;

int  Function (int * a, int * b);

int main() 
{
int a = 2;
int b = 7;
int * x = &a;
int * y = &b;
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
Function (&a , &b);
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
Function (&a , & b);
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
cout << endl << endl; 
cout << a << "   " << *x << endl;
cout << b << "   " << *y << endl;
system ("PAUSE");
return 0;
}
int  Function (int * a, int * b)
{
int pom; 
pom =  *a;
*a = *b; 
*b = pom;        
}

这是普通的通过指针,这改变了一个变量,就像书本学习一样。我感兴趣的是如何通过指针传递 expamle 数组。

你混合了这些概念,这些都不是功能指针

int * Function (int  a, int  b);
int  Function (int * a, int * b);

这:

int * Function (int  a, int  b);

是一个函数,它接受值 2 ints 并返回指向 int 的指针

而这个

int  Function (int * a, int * b);

是一个函数,它接受 2 个指向 int 的指针并返回一个 int