CHAPTER 21. STRUCTURES CHAPTER 21. STRUCTURES
We justcasta pointer to structure to an array ofint’s. And that works! We run the example at 23:51:45 26-July-2014.
0x0000002D (45)
0x00000033 (51)
0x00000017 (23)
0x0000001A (26)
0x00000006 (6)
0x00000072 (114)
0x00000006 (6)
0x000000CE (206)
0x00000001 (1)
The variables here are in the same order as they are enumerated in the definition of the structure:21.8 on page 335.
Here is how it gets compiled:
Listing 21.14: Optimizing GCC 4.8.1
main proc near
push ebp
mov ebp, esp
push esi
push ebx
and esp, 0FFFFFFF0h
sub esp, 40h
mov dword ptr [esp], 0 ; timer
lea ebx, [esp+14h]
call _time
lea esi, [esp+38h]
mov [esp+4], ebx ; tp
mov [esp+10h], eax
lea eax, [esp+10h]
mov [esp], eax ; timer
call _localtime_r
nop
lea esi, [esi+0] ; NOP
loc_80483D8:
; EBX here is pointer to structure, ESI is the pointer to the end of it.
mov eax, [ebx] ; get 32-bit word from array
add ebx, 4 ; next field in structure
mov dword ptr [esp+4], offset a0x08xD ; "0x%08X (%d)\n"
mov dword ptr [esp], 1
mov [esp+0Ch], eax ; pass value to printf()
mov [esp+8], eax ; pass value to printf()
call ___printf_chk
cmp ebx, esi ; meet structure end?
jnz short loc_80483D8 ; no - load next value then
lea esp, [ebp-8]
pop ebx
pop esi
pop ebp
retn
main endp
Indeed: the space in the local stack is first treated as a structure, and then it’s treated as an array.
It’s even possible to modify the fields of the structure through this pointer.
And again, it’s dubiously hackish way to do things, not recommended for use in production code.
Exercise
As an exercise, try to modify (increase by 1) the current month number, treating the structure as an array.
21.3.6 Structure as an array of bytes.
We can go even further. Let’scastthe pointer to an array of bytes and dump it: