Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uint32_t pointer to the same location as uint8_t pointer

#include <iostream>

int main(){
    uint8_t memory[1024];
    memory[0] = 1;
    memory[1] = 1;
    uint32_t *test = memory;
    //is it possible to get a value for *test that would be in this example 257?
}

I want to create a uin32_t pointer to the same adress as the uint8_t pointer. Is this possible without using new(adress)? I don't want to lose the information at the adress. I know pointers are just adresses and therefor I should be able to just set the uint32_t pointer to the same adress.
This code produces an error:

invalid conversion from 'uint8_t*' to 'uint32_t*' in initialization
like image 615
Croxa Avatar asked Oct 17 '25 14:10

Croxa


2 Answers

This would be a violation of so-called Strict Aliasing Rule, so it can not be done. Sad, but true.

Use memcpy to copy data and in many cases compilers will optimize memory copy and generate the same code as they would with cast, but in Standard-conforming way.

like image 145
SergeyA Avatar answered Oct 19 '25 04:10

SergeyA


As already mentioned you cannot convert uint8_t * to uint32_t * due to strict aliasing rule, you can convert uint32_t * to unsigned char * though:

#include <iostream>

int main(){
    uint32_t test[1024/4] = {}; // initialize it!
    auto memory = reinterpret_cast<unsigned char *>( test );
    memory[0] = 1;
    memory[1] = 1;
    std::cout << test[0] << std::endl;
}

this is not portable code due to Endianness, but at least it does not have UB.

like image 45
Slava Avatar answered Oct 19 '25 04:10

Slava