指针注意点
在编程时突然发现指针传值后,不发生变化,故搜索指针在子函数中值不变的相关问题,总结一下,仅作自己记录。
重点: C中函数参数都是传值调用,指针传到子函数,函数对指针进行copy。
通过代码进行说明:
代码一:
指针的基本功能
#include <stdio.h>
static void swap( int *p1 , int *p2 );
static void swap( int *p1 , int *p2 )
{
int temp ;
temp = *p1 ;
*p1 = *p2 ;
*p2 = temp ;
}
int main(/*int argc, char *argv[]*/)
{
int a = 0 , b = 0 ;
int c ,d;
int *point_1 = &c ;
int *point_2 = &d;
printf("input a\n");
scanf ( "%d" , &a) ;
printf("input b\n");
scanf ( "%d" , &b) ;
*point_1 = a ;
*point_2 = b ;
printf ( "\nbefore swap:a= %d, b= %d, c= %d, d= %d\n" , a , b, c, d ) ;
swap ( point_1 , point_2 ) ;
printf ( "\nafter swap:a= %d, b= %d, c= %d, d= %d\n" , a , b, c, d ) ;
}
swap功能是交换两个数, point_1 point_2分别指向c,d,故经过swap变换后, a、b 不变,c、d交换。
结果:
input a
23
input b
34
before swap:a= 23, b= 34, c= 23, d= 34
after swap:a= 23, b= 34, c= 34, d= 23
代码二:
fun1功能:
1、p指向的内容加1,故a执行fun1前为1,执行fun1后为2;
2、p指针指向内容偏移一位(这里偏移一位的大小为int),故p指针原指向0x7ffff3cd1164,故偏移一位指向0x7ffff3cd1168(int占4位)
#include <iostream>
using namespace std;
int func1(int* p);
int func1(int *p)
{
cout << "\nthe address of p itself is " << &p << endl
<< "the address of p point to is " << p << endl;
(*p)++;
p++;
cout << "\nthe address of p itself is " << &p << endl
<< "the address of p point to is " << p << endl;
return 0;
}
int main()
{
int a = 1;
int *p = &a;
cout << "\nbefore : the address of p itself is " << &p << endl;
cout << "before : the address is " << p << " a = " << a << endl;
func1(p);
cout << "\nbefore : the address of p itself is " << &p << endl;
cout << "after : the address is " << p << " a = " << a << endl;
return 0;
}
结果:
before : the address of p itself is 0x7ffff3cd1168
before : the address is 0x7ffff3cd1164 a = 1
the address of p itself is 0x7ffff3cd1138
the address of p point to is 0x7ffff3cd1164
the address of p itself is 0x7ffff3cd1138
the address of p point to is 0x7ffff3cd1168
before : the address of p itself is 0x7ffff3cd1168
after : the address is 0x7ffff3cd1164 a = 2
有结果可看出,函数中的形参p和传入的实参p虽然指向一样的内容,但本身是不同的实参p的自身地址为0x7ffff3cd1168, 形参p自身地址为0x7ffff3cd1138,故对形参p指向内容偏移后,不影响实参p。
图示:
代码三:
主要是参考文献1的内容,即解决指针,子函数,值传递问题:
#include <iostream>
void foo(char *p)
{
p = "after foo()";
}
void main()
{
char *p = "before foo()";
foo(p);
cout <<p <<endl;
}
经过foo变换后,输出的p依旧是”before foo()”,原因,如代码二中描述,只有形参中的内容变了,形参指向新的常量,而实参p没有发生变化。
解决方案:
一、使用return
#include <iostream.h>
char* foo()
{
char* p = "after foo()";
return p;
}
void main()
{
char* p = "before foo()";
p = foo();
cout<<p<<endl;
}
二、使用指针引用
#include <iostream>
void foo(char *& q)
{
q = "after foo()";
}
void main()
{
char *p = "before foo()";
foo(p);
cout <<p <<endl;
}
三、使用指向指针的指针
#include <iostream.h>
void foo(char ** p)
{
*p = "after foo()";
}
void main()
{
char **p = "before foo()";
foo(p);
cout <<*p<<endl;
}