/* struct.c Written by Tanya Amert for Fall 2024. Demonstrates working with structs in C. To compile this program: gcc -Wall -Werror -g -o struct struct.c To run this program: ./struct */ #include // We will define our struct ahead of time. Don't worry about the // extra words (e.g., "typedef") yet -- we'll discuss it soon. typedef struct { int a; // 4 bytes short b; // 2 bytes char c[2]; // two chars, one byte each long d; // 8 bytes char *e; // 8 bytes (we'll talk about why later) } some_data_t; // <-- treat this as a "type" name // Builds a struct and prints its values int main() { // Create a struct of type some_data_t some_data_t data; // Set the fields data.a = 12; data.b = 100; data.c[0] = 48; data.c[1] = 'C'; // why not? this is just the number 67 data.d = 12345678; data.e = "cat"; // Print out some stuff printf("data contains int: %d and short: %d\n", data.a, data.b); printf("data contains long: %ld\n", data.d); // %ld because long decimal integer printf("data contains two chars: %d and %d ('%c' and '%c')\n", data.c[0], data.c[1], data.c[0], data.c[1]); printf("data contains a pointer to a string: \"%s\"\n", data.e); // escape the " so they print return 0; }