我收到一个指针数值,例如:0xbfe0e6ac
,可以将int foo
设置为例如0xbfe0e6ac
的值,它是另一个int内存?
我的场景:
我尝试实现从数组中获取下一个索引的函数,传递指针值(如上面的示例)作为参数。
例如:
char * a = "baa";
char* b = "foo";
printf("%c", cgetnext(&a)); // b
printf("%c", cgetnext(&a)); // a
printf("%c", cgetnext(&b)); // f
printf("%c", cgetnext(&b)); // a
我可以看到执行此操作的唯一方法是:在 cgetnex()
中,将像参数一样传递的数组指针保存到数组中,并且每次调用时,检查作为参数传递的数组之前是否使用过,并且获取它的信息,例如 lasindexused 和 RAM 中的指针值。
这是我的代码:
#include <string.h>
#include <stdlib.h>
typedef struct { int pLocation; int lastIndex; } POINTERINFORMATION;
int __myIndex;
POINTERINFORMATION pointersLocations[256];
int pointersLocationsLength;
char * temparr = NULL;
__myIndex = pointersLocationsLength = 0;
int
plAdd (int p)
{
if (plLen >= sizeof(pointersLocation)) {
return -1;
} else {
pointersLocation[pointersLocationsLength].pLocation = p;
pointersLocation[pointersLocationsLength].lastindex = 0;
pointersLocationsLength ++;
return pointersLocationsLength;
}
}
int
getPointer (int p, POINTERINFORMATION ** out)
{
int i;
for (i = 0; i < pointersLocationsLength; i++)
{
if(pointersLocation[pointersLocationsLength].pLocation == p)
{
*out = makevariablefromponiter(pi.pLocation);
return 1;
}
}
return 0;
}
char
cgetnext(char * arr)
{
char * myarr;
const size_t size = sizeof(char *) + 1;
myarr = malloc(size);
if (NULL == arr){
POINTERINFORMATION * pi;
if (getPointer(p, &pi))
{
__myIndex = pi.lastindex;
myarr = makevariablefromponiter(pi.pLocation);
}
} else {
myarr = strdup (arr);
}
if (strlen(myarr) == __myIndex) {
return '\0';
} else {
__myIndex ++;
temparr = malloc(size);
temparr = strdup(myarr);
return myarr[__myIndex - 1];
}
}
最佳答案
是的,做这样的事情:
int *fooPtr = 0xbfe0e6ac;
foo = *fooPtr;
事实上,您可以使其更加简洁:
foo = *(int *) 0xbfe0e6ac;
关于c - 如何通过 RAM 上的索引设置变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9605155/