#include<iostream>
using namespace std;
void swap1(int a, int b){//a,b只是一份拷贝。值传递
int temp = a;
a = b;
b = temp;
}
void swap2(int *a, int *b){//a,b是指向外部变量的指针。指针传递
int temp = *a;
*a = *b;
*b = temp;
}
void swap3(int *a, int *b){//指针交换了,指针指向的内容没有交换
int *temp;
temp = a;
a = b;
b = temp;
}
void swap4(int &a, int &b ){//a,b是外部变量的引用。引用传递
int temp = a;
a = b;
b = temp;
}
int main(){
int a1 = 6, b1 = 8;
swap1(a1,b1);
cout<<a1<<" "<<b1<<endl;
int a2 = 6, b2 = 8;
swap2(&a2,&b2);
cout<<a2<<" "<<b2<<endl;
int a3 = 6, b3 = 8;
swap3(&a3,&b3);
cout<<a3<<" "<<b3<<endl;
int a4 = 6, b4 = 8;
swap4(a4,b4);
cout<<a4<<" "<<b4<<endl;
return 0;
}
6 8
8 6
6 8
8 6
void GetMemory(char *p)
{
p=(char*)malloc(100);
}
void Test(void)
{
char *str=NULL;
GetMemory(str);
strcpy(str,"hello world");
printf(str);
}
此程序中的函数void GetMemory(char *p)对p的内存改变后,为什么调用函数中str还是一个空指针?为什么对P的改变不能使str改变?
调用函数的时候使用传地址调用则对形参的改变也改变实参,所以你认为对p分配了内存,str也应当被分配了内存,但是这里所说的对形参的改变是对形参所指向的内存中的数进行操作,而你的代码中是对形参分配内存,这与对p指向的内存中的数进行操作而导致str所指向的内存中的数发生改变二者是不同的。
函数调用 编译器总要为形参只做临时副本,代码中只是为副本p分配了内存,str依然为空。
假设str有合法的内存,通过调用使p也指向这块内存,如果利用p使这块内存中的内容发生改变,则str中的内容也会发生改变。
区别以上两种情况~
如果要通过函数调用使str获得合法的内存,改正方法很多:
使用引用:
void GetMemory(char *&p)
使用引用则 p是 str的别名,为p申请内存就是为str申请内存。
使用二重指针:
void GetMemory(char **p)
{
*p=(char*)malloc(100);
}
char *str=NULL;
GetMemory(&str);
strcpy(str,"hello world");
printf(str);
使用函数返回值:
char * GetMemory(char *p)
{
p=(char*)malloc(100);
return p;
}
char *str=NULL;
str = GetMemory(str);
strcpy(str,"hello world");
printf(str);