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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// union fields all share the same space in memory
union IntOrString {
char* as_string;
int as_int;
};
// unions do not know which field you are using
void print_int_or_string(union IntOrString ios) {
// how do I know which one it is?
}
int main(int argc, char* argv[]) {
union IntOrString ios = { .as_int = 5 };
printf("ios.as_int == %d\n", ios.as_int);
// seg fault: address 5 is not accessible
//printf("ios.as_string == %s\n", ios.as_string);
// could also use a data string, but a stack string gives
// a bigger address for this example
char stack_string[] = "Hello";
ios.as_string = stack_string;
printf("ios.as_string == %s\n", ios.as_string);
// .as_int got overwritten when we modified .as_string
printf("ios.as_int == %d\n", ios.as_int);
// just to demonstrate: the int in the union is still 4 bytes
// .as_int is not the full address .as_string as an int
// note: normally we use %p for addresses, but this cast is safe
printf("address of string as long %ld\n", (long)ios.as_string);
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.