C语言小白求问自己定义函数排序哪里有错

C语言小白求问自己定义函数排序哪里有错

问题描述:

#include
void max(int *x, int *y);
int main()
{
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
max(&a, &b);
max(&a, &c);
max(&a, &d);
max(&b, &c);
max(&b, &d);
max(&c, &d);
printf("%d%d%d%d", a, b, c, d);
return 0;
}
void max(int *x, int *y)
{
int *z;
if (*y > *x)
{
*z = *x;
*x = *y;
*y = *z;
}
}

 void max(int *x, int *y)
{
int *z;
if (*y > *x)
{
*z = *x;
*x = *y;
*y = *z;
}
}

改为

 void max(int *x, int *y)
{
int z;
if (*y > *x)
{
z = *x;
*x = *y;
*y = z;
}
}

int *z是一个非法指针,你可以把*z替换成z就行了

#include

using namespace std;
void fun_swap1(int a,int b)
{
a=a^b;
b=a^b;
a=a^b;
cout << "值传递函数内" << endl;
cout << "a=" << a <<endl;
cout << "b=" << b <<endl;
}
void fun_swap2(int *a,int *b)
{
*a=*a^*b;
*b=*a^*b;
*a=*a^*b;
cout << "地址传递函数内" << endl;;
cout << "a=" << *a << endl;
cout << "b=" << *b <<endl;
}
void fun_swap3(int &a,int &b)
{
a=a^b;
b=a^b;
a=a^b;
cout << "值引用函数内" << endl;
cout << "a=" << a <<endl;
cout << "b=" << b <<endl;
}
void fun_swap4(int *a,int *b)
{
int *t;
t=a;
a=b;
b=t;
cout << "地址交换函数内" << endl;;
cout << "a=" << *a << endl;
cout << "b=" << *b <<endl;
}
int main()
{
cout << "Hello world!" << endl;
int x1=1;
int y1=2;
fun_swap1(x1,y1);
cout << "值传递之后" << endl;
cout << "x1=" << x1 <<endl;
cout << "y1=" << y1 <<endl;
int x2=1;
int y2=2;
fun_swap2(&x2,&y2);
cout << "地址传递之后" << endl;
cout << "x2=" << x2 <<endl;
cout << "y2=" << y2 <<endl;
int x3=1;
int y3=2;
fun_swap3(x3,y3);
cout << "值引用之后" << endl;
cout << "x3=" << x3 <<endl;
cout << "y3=" << y3 <<endl;
int x4=1;
int y4=2;
fun_swap4(&x4,&y4);
cout << "地址交换之后" << endl;
cout << "x4=" << x4 <<endl;
cout << "y4=" << y4 <<endl;
return 0;
}


定义指针的时候,要告诉指针指向什么,不可以这样直接赋值