My book is attempting to familiarize me with concepts such as pointer dereferencing concerning structures and some weird ways of accessing structures. I am a newbie, and find the following confusing about the code below.
#include <stdio.h>
#include <time.h>
void dump_time_struct_bytes(struct tm *time_ptr, int size) {
int i;
unsigned char *raw_ptr;
printf("bytes of struct located at 0x%08x\n", time_ptr);
raw_ptr = (unsigned char *)time_ptr;
for (i = 0; i < size; i++)
{
printf("%02x ", raw_ptr[i]);
if (i % 16 == 15) // Print a newline every 16 bytes.
printf("\n");
}
printf("\n");
}
int main() {
long int seconds_since_epoch;
struct tm current_time, *time_ptr;
int hour, minute, second, i, *int_ptr;
seconds_since_epoch = time(0); // Pass time a null pointer as argument.
printf("time() - seconds since epoch: %ld\n", seconds_since_epoch);
time_ptr = ¤t_time; // Set time_ptr to the address of
// the current_time struct.
localtime_r(&seconds_since_epoch, time_ptr);
// Three different ways to access struct elements:
hour = current_time.tm_hour; // Direct access
minute = time_ptr->tm_min; // Access via pointer
second = *((int *)time_ptr); // Hacky pointer access
printf("Current time is: %02d:%02d:%02d\n", hour, minute, second);
dump_time_struct_bytes(time_ptr, sizeof(struct tm));
minute = hour = 0; // Clear out minute and hour.
int_ptr = (int *)time_ptr;
for (i = 0; i < 3; i++) {
printf("int_ptr @ 0x%08x : %d\n", int_ptr, *int_ptr);
int_ptr++; // Adding 1 to int_ptr adds 4 to the address,
} // since an int is 4 bytes in size.
}
Output:
time() - seconds since epoch: 1189311744
Current time is: 04:22:24
bytes of struct located at 0xbffff7f0
18 00 00 00 16 00 00 00 04 00 00 00 09 00 00 00
08 00 00 00 6b 00 00 00 00 00 00 00 fb 00 00 00
00 00 00 00 00 00 00 00 28 a0 04 08
int_ptr @ 0xbffff7f0 : 24
int_ptr @ 0xbffff7f4 : 22
int_ptr @ 0xbffff7f8 : 4
i. I understand that the author has redeclared *time_ptr as a pointer to unsigned char, but how did it manage to become an array (character array, I think)? I think that this might be to do with the fact that arrays are interpreted as pointers which point to their 0th elements, but I am not sure.
ii. Secondly, what is the output from the dump_time_struct_bytes function (the dumped bytes)? I understand that thats the bytes from the structure, but I dont know how they are supposed to make up the 4 hours, 22 minutes and 24 seconds stored in it (if this is the case at all). Also, what does the address of *time_ptr correspond to? Is it the start of the structure? If the latter is true, do the corresponding dumped bytes in the output belong only to its first element (tm_sec) or to the whole structure ?
The explanation for the "hacky pointer" was a bit weird- why does dereferencing a converted integer pointer solely reveal the contents of the first element in the structure- tm_sec?
Thank you in advance.