C Programming: Swapping Values Using Pointers
The code you provided has a few syntax errors. Here is a corrected version:
#include <stdio.h>
int main() { int a = 10, b = 20, *p1, *p2, *p; p1 = &a; p2 = &b;
if (a < b) {
p = p1;
p1 = p2;
p2 = p;
}
printf("%d, %d\n", a, b);
printf("%d, %d\n", *p1, *p2);
return 0;
}
This program declares two integer variables 'a' and 'b', as well as three integer pointers 'p1', 'p2', and 'p'. It then initializes 'a' to 10 and 'b' to 20, and assigns the address of 'a' to 'p1' and the address of 'b' to 'p2'.
The program then checks if 'a' is less than 'b'. If it is, it swaps the values of 'p1' and 'p2' using a temporary pointer 'p'.
Finally, the program prints the values of 'a' and 'b' using 'printf', followed by the values that 'p1' and 'p2' point to (which may or may not be the same as the original values of 'a' and 'b').
原文地址: https://www.cveoy.top/t/topic/ol5g 著作权归作者所有。请勿转载和采集!