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

时间:2017-07-28 16:58:17

标签: c++ pointers

我有这些代码......

#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;

}

这是函数指针,不更改变量。我不知道为什么,以及Fucntion指针的确切含义。为什么这种指针有用?

对战

  #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数组。

1 个答案:

答案 0 :(得分:1)

你正在混合概念,没有一个功能指针

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

这样:

int * Function (int  a, int  b);

是一个按值2整数取值并返回指向int

的指针的函数

和这个

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

是一个函数,它使用2个指向int并返回一个int