swap( int* p1,int* p2 ) { int *p; *p = *p1; *p1 = *p2; *p2 = *p; }
初始化int*p = NULL也不对,p还是一个野指针,没有自己指向的内存,如果非要用int*p的话, 可以给p分配一个内存,不过记得释放掉 #include <stdio.h> #include <stdlib.h> using namespace std; void swap(int* p1, int* p2){ int* p = NULL; p = (int*)malloc(4); *p = *p1; *p1 = *p2; *p2 = *p; free(p); } int main(){ int a = 2,b = 3; swap(&a, &b); printf("%d,%d\n", a, b); system("Pause"); return 0; }