#include <stdio.h>
void swap(int p, int c )
{
int t;
t = p; p = c; c = t;
}
void main()
{
int b[2] = { 3,5 };
printf("%d %d\n", b[0], b[1]);
swap(b[0], b[1]);
printf("%d %d", b[0], b[1]);
}
void swap(int p, int c )中p,c是值传递,也就是b[0], b[1]的复制品,对他们的修改不会影响到b[0], b[1]。
改用指针 void swap(int *p, int *c )
#include <stdio.h>
void swap(int *p, int *c )
{
int t;
t = *p; *p = *c; *c = t;
}
void main()
{
int b[2] = { 3,5 };
printf("%d %d\n", b[0], b[1]);
swap(&b[0], &b[1]);
printf("%d %d", b[0], b[1]);
}
#include <stdio.h>
void swap(int b[],int p, int c )
{
int t;
t = b[p]; b[p] = b[c]; b[c] = t;
}
int main()
{
int b[2] = { 3,5 };
printf("%d %d\n", b[0], b[1]);
swap(b, 0, 1);
printf("%d %d", b[0], b[1]);
}