Pointer to different data type in C -
i have compiled , run following program in c:
#include <stdio.h> #include <stdint.h> #include <inttypes.h> int main(int argc, char* argv[]){ uint8_t data[8] = {0, 1, 2, 3, 4, 5, 6, 7}; uint32_t* pointer32 = &data[0]; uint64_t* pointer64 = &data[0]; printf("%" priu64 "\n", *pointer64); printf("%" priu32 "\n", *(pointer32++)); printf("%" priu32 "\n", *pointer32); return 0; }
and received following expected output:
506097522914230528 50462976 117835012
the output correct , corresponds bitwise interpretation of data unsigned 64-bit integer , unsigned 32-bit integers. tried on 64-bit machine running ubuntu 14.04. compiled stock gcc compiler (4.8.4?). compiler throw "assignment incompatible pointer type" warning (which can safely ignored because incompatible assignment intended).
is reliable way of converting , interpreting data in "data" array, or better recommended manually copy , shift each byte, 1 @ time, temporary variable?
you violating aliasing rules. so, clear answer is: no.
briefly: must not have pointers of different type pointing same object. may result in broken code, compiler assume not happen , might optimize code.
just strong hint: not ignore warnings. given reasons.
the best way serialize/deserialize data array per element final types. avoid problems endianess (byte-ordering) of values , (possible) padding.
i use functions this:
uint32_t readuint32(const uint8_t **buffer) { ... // increment buffer accordingly }
this way, pass buffer pointer along line, without having care incrementing in caller. technic iterator.
Comments
Post a Comment