c - 如何通过 RAM 上的索引设置变量值?

标签 c pointers memory-management

我收到一个指针数值,例如: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/

相关文章:

C 数组 : setting element at offset

c - 代码是否自上而下阅读

c - 动态矩阵数组

c - 使用 malloc 后无法复制数组

c# - 是否有一个 .Net 内存分析器可以跟踪大对象堆上的所有分配?

objective-c - 让成员变量保留而不是分配是更好的做法吗

C- 字符串和循环

c++ - 如何调整 AVFrame 的大小?

c - C 中奇怪的段错误

c - C 中 int *[5] 和 int (*)[5] 有什么区别?