You can clarify it a bit by changing the printf to printf("%d ", p[i]);
.
What the code does is to iterate across an array of int
byte by byte. A special rule in C allows us to inspect the raw data of pretty much any type, by using a pointer to character type and then access individual bytes.
char
is however a very poor choice because of Is char signed or unsigned by default?. Use unsigned char
or uint8_t
instead.
As for why the raw byte presentation of an int
with value 1
comes up as 1 0 0 0
, it's because your systems happens to be a 32 bit int
little endian system. What is CPU endianness?
The if (i % sizeof(t[0]) == sizeof(t[0]) - 1) printf("\n");
part is just to print the new line after 4 bytes.
A complete rewrite of the program might look like this:
#include <stdio.h>
int main (void)
{
int t[] = { 1, 2 };
const size_t t_items = sizeof(t)/sizeof(*t); // 8/4 = 2 items
unsigned char* p = (unsigned char*)t; // bug fix to make the code portable
for (size_t i = 0; i<t_items; i++) // iterate across array items
{
for(size_t j=0; j<sizeof(int); j++) // iterate across the bytes of each int
{
printf("%d ", *p);
p++;
}
printf("\n");
}
}