在C编程语言中,如何手动分配指针地址(例如将其分配到内存地址0x28ff44
)?
在C编程语言中,如何手动分配指针地址(例如将其分配到内存地址0x28ff44
)?
就像这样:
void * p = (void *)0x28ff44;
或者如果你想要一个char *
类型:
char * p = (char *)0x28ff44;
如果你指向的是真正不应该改变的东西,就加上const
关键字:
const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;
我想这肯定是某种“众所周知的地址”,通常(但并不总是)是只读的。
const
,但它所指向的数据不是。大多数程序员从未看到过这段代码,也不知道它是如何工作的。虽然我可以补充一下 - 这正是C仍然最相关的地方,因为越来越少的应用软件有任何真正需要用C编写的理由。 - Brian McFarland你的代码应该像这样:
int *p = (int *)0x28ff44;
int
需要是您引用的对象的类型,或者可以是void
。
但要小心不要访问不属于您程序的内容。
int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address
unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned
假设您想要一个指针指向地址0x28ff4402,通常的方法是
uint32_t *ptr;
ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
*ptr |= (1<<13) | (1<<10); //access the address how ever you want
#define ptr *(uint32_t *) (0x28ff4402)
#define ptrVar (*((volatile unsigned long *)0x400073FC)) //ptrVar points to memory location 0x400073FC
ptrVar =10// write 10 at the memory location