CHAPTER 21. STRUCTURES CHAPTER 21. STRUCTURES
add eax, 1900
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aYearD ; "Year: %d\n"
call printf
mov eax, [esp+30h+tm_mon]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aMonthD ; "Month: %d\n"
call printf
mov eax, [esp+30h+tm_mday]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aDayD ; "Day: %d\n"
call printf
mov eax, [esp+30h+tm_hour]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aHourD ; "Hour: %d\n"
call printf
mov eax, [esp+30h+tm_min]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aMinutesD ; "Minutes: %d\n"
call printf
mov eax, [esp+30h+tm_sec]
mov [esp+30h+var_2C], eax
mov [esp+30h+var_30], offset aSecondsD ; "Seconds: %d\n"
call printf
leave
retn
main endp
This code is identical to what we saw previously and it is not possible to say, was it a structure in original source code or just
a pack of variables.
And this works. However, it is not recommended to do this in practice. Usually, non-optimizing compilers allocates variables
in the local stack in the same order as they were declared in the function. Nevertheless, there is no guarantee.
By the way, some other compiler may warn about thetm_year,tm_mon,tm_mday,tm_hour,tm_minvariables, but not
tm_secare used without being initialized. Indeed, the compiler is not aware that these are to be filled bylocaltime_r()
function.
We chose this example, since all structure fields are of typeint. This would not work if structure fields are 16-bit (WORD), like
in the case of theSYSTEMTIMEstructure—GetSystemTime()will fill them incorrectly ( because the local variables are
aligned on a 32-bit boundary). Read more about it in next section: “Fields packing in structure” (21.4 on page 343).
So, a structure is just a pack of variables laying on one place, side-by-side. We could say that the structure is the instruction
to the compiler, directing it to hold variables in one place. By the way, in some very early C versions (before 1972), there
were no structures at all [Rit93].
There is no debugger example here: it is just the same as you already saw.
21.3.5 Structure as an array of 32-bit words
#include <stdio.h>
#include <time.h>
void main()
{
struct tm t;
time_t unix_time;
int i;
unix_time=time(NULL);
localtime_r (&unix_time, &t);
for (i=0; i<9; i++)
{
int tmp=((int*)&t)[i];
printf ("0x%08X (%d)\n", tmp, tmp);
};
};