引用博文:https://www.cnblogs.com/WeyneChen/p/6672045.html
函数参数传递的只能是数值,所以当指针作为函数参数传递时,传递的是指针的值,而不是地址。
当指针作为函数参数传递时,在函数内部重新申请了一个新指针,与传入指针指向相同地址。在函数内部的操作只能针对指针指向的值。
#include <iostream> using namespace std; void pointer(int *p) { int a = 11, c = 33; printf("\n\nEnter function"); printf("\nthe p is point to %p , p's addr is %X, *p is %d", p, &p, *p); *p = a; printf("\nthe p is point to %p , p's addr is %X, *p is %d", p, &p, *p); p = &c; printf("\nthe p is point to %p , p's addr is %X, *p is %d", p, &p, *p); printf("\nfunction return\n"); } int main() { int b = 22; int *p = &b; printf("the b address %X\n", &b); printf("the p is point to %p , p's addr is %X, *p is %d", p, &p, *p); pointer(p); printf("\nthe p is point to %p , p's addr is %X, *p is %d\n", p, &p, *p); }
运行结果:
the b address 003DFC98 the p is point to 003DFC98 , p's addr is 3DFC8C, *p is 22 Enter function the p is point to 003DFC98 , p's addr is 3DFBB8, *p is 22 the p is point to 003DFC98 , p's addr is 3DFBB8, *p is 11 the p is point to 003DFB98 , p's addr is 3DFBB8, *p is 33 function return the p is point to 003DFC98 , p's addr is 3DFC8C, *p is 11 请按任意键继续. . .
1. 在没有进入pointer函数之前,变量p存储的值为003DFC98,变量p的地址为3DFC8C,*p的值等于b的值等于22。
2. 进入pointer之后,p所指向的内存地址没有改变,但是p自身的地址变了。意味着函数传递只是将003DFC98传递进来了。虽然这个指针变量名字还是叫做p,但与main函数中的指针变量已经不一样了。这意味着,你可以改变main函数中b的值,但是不能改变p的值。
函数参数为指针的指针 (双重指针)
#include <iostream> using namespace std; void GetMemory(char *p, int num) { p = (char*)malloc(sizeof(char)*num); } void main() { char *s = NULL; GetMemory(s, 100); strcpy(s, "hello"); printf(s); }
GetMemory这个函数是调用malloc申请一块内存。乍一看好像没什么问题,编译也不会报错。但是运行起来,程序直接奔溃。 其实有了上面的分析就可以知道,GetMemeory中的p是不能改变s的指向的,也就是说s还是指向NULL。GetMemory中的P是临时申请的一个指针变量,当s传值进来(NULL),时,p指向NULL,除此之外,没做任何改变。当运行malloc函数后,也只是将malloc返回的的指针地址赋给了p,并不能传递给s。所以这里就需要指针的指针(双重指针)了。
#include <iostream> using namespace std; void GetMemory(char **p, int num) { *p = (char*)malloc(sizeof(char)*num); } void main() { char *s = NULL; GetMemory(&s, 100); strcpy(s, "hello\n"); printf(s); }
这个时候就是将指针变量s的地址传递了过去,而不是将指针变量的值(NULL)传递了过去,因此就可以改变s的指向了。