/* arrays.c Tanya Amert, Fall 2023 How do array accesses get represented in x86-64? Compile for debugging via gdb: gcc -g -Og -o arrays arrays.c Run with no command-line arguments: ./arrays */ #include #include #define NUM_BYTES 40 typedef unsigned char * byte_ptr; void show_bytes(byte_ptr start, size_t len) { int i; for (i = 0; i < len; i++) { printf(" %.2x", start[i]); } printf("\n"); } int main() { // Allocate 40 bytes, which is enough for a char[] with // 40 elements, or a short[] with 20 elements, or an int[] // with 10 elements, or a long[] with 5 elements void *p = malloc(NUM_BYTES); // We can cast p to different types char *p_char = (char *)p; short *p_short = (short *)p; int *p_int = (int *)p; long *p_long = (long *)p; // Set the values such that byte at index b has value b for (int i = 0; i < NUM_BYTES; i++) { p_char[i] = i; } // Now let's access different elements char a30 = p_char[30]; // p + ?? short s17 = p_short[17]; // p + ?? int i7 = p_int[7]; // p + ?? long l3 = p_long[3]; // p + ?? // Print these values printf("\nValues in hex:\n-------------\n"); printf(" char at index 30: %x\n", a30 & 0xFF); printf("short at index 17: %x\n", s17 & 0xFFFF); printf(" int at index 7: %x\n", i7); printf(" long at index 3: %lx\n", l3); // Now print the bytes they contain printf("\nValues in byte order:\n-------------\n"); printf(" char at index 30:"); show_bytes(&a30, sizeof(char)); printf("short at index 17:"); show_bytes((byte_ptr)&s17, sizeof(short)); printf(" int at index 7:"); show_bytes((byte_ptr)&i7, sizeof(int)); printf(" long at index 3:"); show_bytes((byte_ptr)&l3, sizeof(long)); // Now iterate through the bytes as if different arrays char sum_char = 0; for (int i = 0; i < NUM_BYTES / sizeof(char); i++) { sum_char += p_char[i]; } printf("\nSum of char values: %x\n", sum_char & 0xFF); short sum_short = 0; for (int i = 0; i < NUM_BYTES / sizeof(short); i++) { sum_short += p_short[i]; } printf("\nSum of short values: %x\n", sum_short & 0xFFFF); int sum_int = 0; for (int i = 0; i < NUM_BYTES / sizeof(int); i++) { sum_int += p_int[i]; } printf("\nSum of int values: %x\n", sum_int); long sum_long = 0; for (int i = 0; i < NUM_BYTES / sizeof(long); i++) { sum_long += p_long[i]; } printf("\nSum of long values: %lx\n", sum_long); return 0; }