c - Pointer Upcast and Downcast -


pointer downcast

    int* ptrint;     char * ptrchar;     void* ptrvoid;     unsigned char indx;     int sample = 0x12345678;      ptrint = &sample;     ptrvoid = (void *)(ptrint);     ptrchar = (char *)(ptrvoid);      /*manipulating ptrchar */     (indx = 0; indx < 4; indx++)     {         printf ("\n value: %x \t address: %p", *(ptrchar + indx), ( ptrchar + indx));      } 

output:

 value: 00000078         address: 0022ff74  value: 00000056         address: 0022ff75  value: 00000034         address: 0022ff76  value: 00000012         address: 0022ff77 

question: why sample divided char sized data? , when pointer arithmetic performed, how able remaining value? how possible?


pointer upcast

unsigned int * ptruint; void * ptrvoid; unsigned char sample = 0x08;  ptrvoid = (void *)&sample; ptruint = (unsigned int *) ptrvoid;  printf(" \n &sample: %p \t ptruint: %p ", &sample, ptruint ); printf(" \n sample: %p \t *ptruint: %p ", sample, *ptruint );   

output:

 &sample: 0022ff6f       ptruint: 0022ff6f  sample: 00000008        *ptruint: 22ff6f08    <- problem point 

question: why there garbage value in *ptruint? why garbage value similar ptruint? should malloc() or calloc() used avoid garbage value? kind of remedy suggest remove garbage value?

in first example, using char pointer data going accessed byte @ time. memory byte addressable, when add 1 pointer, access next higher memory address. happening loop. using byte pointer tells compiler access single byte, , rest of bits show 0 when printing %p.

in second example, think happening 1 byte allocated sample byte, following 4 bytes allocated ptruint. when value starting @ memory address of sample , converting 4 byte pointer, see value in sample plus first 3 bytes of ptruint. if cast char pointer, , print, see 8 in output.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -