Reputation: 97
typedef unsigned char uint8_t;
typedef int uint32_t;
uint8_t Local_Buffer[2] = {1,3};
uint32_t d_buffer;
d_buffer = ( *(uint32_t *)Local_Buffer );
What is the content of d_buffer
in the end? After printing value of d_buffer, i get 0x70820301. So its an address.
Upvotes: 0
Views: 58
Reputation: 19032
You're setting up a local buffer of 2 bytes with the values 1, 3, like this:
|0x01|0x03|
Then you're casting that value (using C
-style casts) to a pointer to a uint32_t
, dereferencing that and stroing the result. uint32_t
is 4 bytes in size.
Logically, it may seem that you are getting d_buffer
to have some values like:
|0x01|0x03|?|?
In reality, this cast reads past the ends of an array, and therefore evokes undefined behavior, so literally anything could happen.
In your particular case, it appears you're getting d_buffer
populated with the expected values (0x03,0x01) along with two other "random" values from the adjacent memory address.
The endianness of your architecture will tell you how the individual bytes are stored to make up the value of your uint32_t
value. Your value of 0x70820301
shows that 0x0301
are stored as expected, along with the "unexpected" garbage values of 0x70820000
.
Upvotes: 5
Reputation: 7625
( *(uint32_t *)Local_Buffer );
here Local_Buffer
decays to unsigned char*
, which points to the first element of the array. You are casting it to int*
and then de-referencing it. You code has Undefined Behavior, since the array is of size 2, where an int
has in most platform atleast size 4. Accessing it as int
will pass beyond the memory, and what will happen while accessing that memory is undetermined.
Upvotes: 2