casting with pointers

The below example confuses me a little. Basically, we have an unsigned 64 bit integer initialized to 0. Then we use the type cast operator, which will cast to an unsigned 8-bit integer pointer, to cast the first memory address of val. I believe we do this because when we start assigning values to the pointer, the first address and then subsequent addresses of val will reference them too.

uint64_t val = 0;
uint8_t * p = (uint8_t *)&val;

Is this interpretation correct?
Is this interpretation correct?

I'm too stupid to give a straight yes/no answer so I'll just explain this myself all over again.

First you define and initialize an unsigned integer named val.
It will use 64 bits (8 bytes) of memory.

Next you take the address of val and store it in a pointer to unsigned integer of 8 bits (1 byte) named p.

Basically, your p can now be used as an array containing eight uint8_t elements. Those eight "elements" put together make up val.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    uint64_t val = 0;
    uint8_t *p = (uint8_t *)&val;

    p[0] = 0xEF;
    p[1] = 0xBE;
    p[2] = 0xAD;
    p[3] = 0xDE;
    p[4] = 0xFE;
    p[5] = 0xCA;
    p[6] = 0xAF;
    p[7] = 0xDE;

    printf("%llX\n", val);
}
DEAFCAFEDEADBEEF


You shouldn't be doing this.

Unsigned integers tend to be well behaved, but if you try this trick with a 32-bit float or 64-bit double, all you will get is garbage.
uint64_t val = 0;
uint8_t * p = (uint8_t *)&val;


yes, this is valid c/c++, is it correct? depends what you wanted to achieve.


p is now a pointer to the memory where val is stored, p also thinks that bytes are there.

the bytes can be accessed *p *(p+1) *(p+2) etc....

a quirk of how static arrays are implemented lets you do what catfish said, p[0] p[1] p[2] ...
Topic archived. No new replies allowed.