ポインターダウンキャスト
int* ptrInt;
char * ptrChar;
void* ptrVoid;
unsigned char indx;
int sample = 0x12345678;
ptrInt = &sample;
ptrVoid = (void *)(ptrInt);
ptrChar = (char *)(ptrVoid);
/*manipulating ptrChar */
for (indx = 0; indx < 4; indx++)
{
printf ("\n Value: %x \t Address: %p", *(ptrChar + indx), ( ptrChar + indx));
}
出力:
Value: 00000078 Address: 0022FF74
Value: 00000056 Address: 0022FF75
Value: 00000034 Address: 0022FF76
Value: 00000012 Address: 0022FF77
質問: サンプルが char サイズのデータに分割されたのはなぜですか? また、ポインター演算が実行された場合、どのようにして残りの値を取得できたのでしょうか? これはどのように可能でしたか?
ポインターのアップキャスト
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 );
出力:
&sample: 0022FF6F ptrUint: 0022FF6F
sample: 00000008 *ptrUint: 22FF6F08 <- Problem Point
質問: *ptrUint にガベージ値があるのはなぜですか? ガベージ値が ptrUint に似ているのはなぜですか? このガベージ値を回避するには、malloc() または calloc() を使用する必要がありますか? ガベージ値を削除するには、どのような救済策を提案しますか?