c - Casting a (ptr to const ) to (ptr to uint8) -


is there way in "c" cast (ptr const structure ) (ptr uint8)

the following function expects (ptr uint8)

memcopy( (uint8 *) destination, (uint8 *) source , uint16 _size); 

the function intends copy buffer of type ((ptr const)) buffer

i'm aware in c++ may use const_cast cast away (remove) constness or volatility. how c ?

the current case follow: have structure main_s

struct main_s { strcut1 xxxx1 strcut2 xxxx2 strcut3 xxxx3 } 

the pointer main_s strcut (ptrcnst_main) , it's pointer const.

i need copy 2nd element (xxxx2) of main_s i'll following

strcut2 dest; memcopy( (uint8 *) &destination, (uint8 *) ptrcnst_main->xxxx2 , sizeof(strcut2)); 

but never works. , keep having error cant cast ptr const ptr-uint8

update

i read comments, it's getting strange... code approximative i'll try solve problem.

strcut2 dest; memcopy( (uint8 *)&dest, (uint8 *)&(ptrcnst_main->xxxx2) , sizeof(strcut2)); 

try add ampersand (&) in front of ptrcnst_main->xxxx2 , put parantheses did.


usually, when copying data buffer without applying changes source buffer, declare variable constant pointer because it won't change! it's source buffer. here, pointer source should const uint8 *source. if it's constant pointer, able read value inside.

put const qualifier on non-mutable data (read "data doesn't need change"), practice , every of colleagues.

conclusion don't need cast const non-const. constant variable still can read.

however, answer original question :

is there way in "c" cast (ptr const) (ptr uint8)?

in c, cast follow: (type) variable

for example :

const char* c1 = malloc(sizeof(char) * 5); char* c2 = (char*)c1; // cast here (int = 0; < 5 ; i++) {    c2[i] = 'i'; } printf("%s\n", c1); 

but it's bad practice remove constness. if it's constant, it's on purpose.

note : code bad on lots of point, kept simple demonstration purpose.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -