gpt4 book ai didi

c - 指针向上转换和向下转换

转载 作者:太空宇宙 更新时间:2023-11-04 04:05:27 25 4
gpt4 key购买 nike

指针向下转换

    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

问题:为什么样本被分成字符大小的数据?而当指针运算时,它是如何得到它的剩余值的呢?这怎么可能?


指针向上转换

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 中有垃圾值?为什么垃圾值相似委托(delegate)?应该使用 malloc() 还是 calloc() 来避免这个垃圾值?您建议采取何种补救措施来消除垃圾值?

最佳答案

在第一个示例中,您使用的是 char 指针,因此将一次访问一个字节的数据。内存是字节寻址的,所以当你给一个指针加一时,你将访问下一个更高的内存地址。这就是 for 循环发生的情况。使用字节指针告诉编译器只访问单个字节,当您使用 %p 打印时,其余位将显示为 0。

在第二个例子中,我认为发生的事情是一个字节被分配给样本字节,然后接下来的 4 个字节被分配给 ptrUint。因此,当您获取从 sample 的内存地址开始的值并将其转换为 4 字节指针时,您只会看到 Sample 中的值加上 ptrUint 的前 3 个字节。如果将其转换为字符指针并打印,则输出中只会看到 8。

关于c - 指针向上转换和向下转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6561630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com