#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改变?