指针运算的问题。 [英] Problems with pointer arithmetic.

查看:72
本文介绍了指针运算的问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我已经使用malloc()分配了一些内存,操作系统会给我分配的内存地址(即一个页面)。现在我试图浏览这个内存区域,好像它是一个16位的地址空间,从0开始,以0xFFFF结束。 (不要问为什么!,只是想了解一些概念)

所以我编写了这个例程,将所谓的虚拟地址转换为物理地址:

Hi,
Say I've allocated some memory using malloc(), the operating system will give me the address to the memory allocated (i.e. a page). Now I am trying to browse this area of memory as if it was a 16-bit address space which starts from 0 and ends at 0xFFFF. (Don't ask why!, Just wanted to understand some concepts)
So I wrote this routine which will convert the so-called "virtual" address into a physical one:

uint32_t* virtual_to_physical(uint16_t OFFSET, uint32_t* MEMORY_BUFFER)
{
	uint32_t* a = MEMORY_BUFFER + OFFSET;
	return a;
}



基本上这个例程将获得malloc()ed缓冲区,然后添加偏移量并返回物理地址。

现在当我这样尝试时:


Basically this routine will get the malloc()ed buffer and then will add the offset and return the physical address.
Now when I try it like this:

uint32_t* physaddr = (uint32_t*)malloc(0xFFFF);
printf("\nmalloc()ed buffer: %p", physaddr);
uint32_t* new_addr = virtual_to_physical(1, physaddr); //! Get the physical address of offset 1 in the malloc()ed buffer
printf("\nVirtual Address 1 turned to physical address: %p", (uint32_t*)new_addr);



但我得到的输出是:


But the output I get is:

malloc()ed buffer: 0x12b90a0
Virtual Address 1 turned to physical address: 0x12b90a4



而不是添加1到物理地址它增加4?


Instead of adding 1 to the Physical address it increments it by 4?

推荐答案

是的。它确实 - 这就是我所期望的。

想一想:你的内存缓冲区有什么数据类型?它是一个uint32_t(因为MEMORY_BUFFER被声明为指向uint32_t的指针),这意味着它可以处理32位数量,所以当你向指针添加1时,它会将它移动到下一个uint32_t值,而不是内存中的下一个字节。物理地址总是以字节为单位 - 或者当你使用字符r字节值时你不会保存任何内存空间 - 但是指针总是指向指针类型的整数值 - 或者向上移动整数数组做一个PITA! :笑:



如果你想以字节为增量工作,那么使用指向系统中无符号字符或其他8位数据类型的指针。
Yes. It does - that is what I would expect.
Think about it: What datatype is your memory buffer? It's a uint32_t (because MEMORY_BUFFER is declares as a pointer to uint32_t) which means it addresses 32 bit quantities, so when you add 1 to the pointer it moves it to the next uint32_t values, not the next byte in the memory. Physical addresses are always in bytes - or you wouldn't save any memory space when you used characters r byte values - but pointers always point to a "whole" value of the type of the pointer - or moving up through an array of integers would be a PITA! :laugh:

If you want to work in byte increments, then use a pointer to an unsigned char, or other 8 bit datatype in your system.


这篇关于指针运算的问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆