1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#define print_int_expr_and_value(n) printf("%s == %d\n", (#n), (n))
#define print_address_expr_and_value(a) printf("%s == %p\n", (#a), (void*)(a))
// WRONG swap_wrong(…)
void swap_wrong(int** a_a_lhs, int** a_a_rhs) {
// Relative to memory form: a_a_lhs == 228 a_a_rhs == 236
int* a_lhs = *a_a_lhs; // a_a_lhs is an int** *a_a_lhs is an int*
int* a_rhs = *a_a_rhs;
// Relative to memory form: a_lhs == 220 a_a_rhs == 224
// Relative to memory form: *a_a_lhs == 220 *a_a_rhs == 224
*a_a_lhs = a_rhs; // "Store a_rhs at (address) a_a_lhs." // This affects a_n1 not n1.
*a_a_rhs = a_lhs; // "Store a_lhs at (address) a_a_rhs." // This affects a_n2 not n2.
// Relative to memory form: a_lhs == 220 a_a_rhs == 224 (no change)
// Relative to memory form: *a_a_lhs == 224 *a_a_rhs == 220
}
int main(int argc, char* argv[]) {
int n1 = 3;
int n2 = 100;
print_int_expr_and_value(n1);
print_int_expr_and_value(n2);
int* a_n1 = &n1; // These got swapped.
assert(*a_n1 == n1); // obvious
int* a_n2 = &n2;
assert(*a_n2 == n2); // obvious
print_address_expr_and_value(a_n1);
print_address_expr_and_value(a_n2);
swap_wrong(&a_n1, &a_n2);
assert(*a_n1 == n1); // shouldn't this obvious???? ... yet this time it fails.
assert(*a_n2 == n2); // "
print_int_expr_and_value(n1);
print_int_expr_and_value(n2);
print_address_expr_and_value(a_n1);
print_address_expr_and_value(a_n2);
print_int_expr_and_value(*a_n1);
print_int_expr_and_value(*a_n2);
/* printf("\nCalled swap_wrong(…)\n"); */
/* print_int_expr_and_value(n1); */
/* print_int_expr_and_value(n2); */
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.