malloc:从内存中获取信息

问题描述 投票:-1回答:1

我目前正在做一个项目来模拟加载和存储信息,例如计算机缓存。

我使用malloc将结构加载到内存中,但是我不知道如何再次检索该信息。对于任何一行,我都需要能够调用缓存中的特定行,并查看它是否像缓存一样导致“命中或未命中”。

struct cache {int s; int E; int b;}; //my struct

//creating a similated cache in memory.
struct cache** c1 = (struct cache**) malloc( pow(2,ssize) * Esize * sizeof(struct cache));`
c caching malloc
1个回答
0
投票

基本上是您做的

struct cache** c1 = (struct cache**) malloc( pow(2,ssize) * Esize * sizeof(struct cache)). 

这是指向结构缓存的指针。它类似于指向结构缓存的指针数组,但是它不在您的堆栈内存中,而是在您的堆内存中。但是,您做错了。您的结构缓存**的每个索引都假定等于结构缓存的指针的大小。下面的代码可能解释了所有内容。

获得结构缓存**的空间后,您想为其每个索引分配一个指向struct * cache的指针,或者malloc一个指向结构缓存的指针,其大小等于结构缓存的大小。下面的代码,我使用malloc创建了10个索引。所以0-9。

#include <stdlib.h>
#include <stdio.h>


struct cache {int s; int E; int b;}; //my struct

//creating a similated cache in memory.
int main(){
    // Each index equal the size of a pointer to struct cache and there is 10 index
    struct cache** c1 = (struct cache**) malloc( sizeof( struct cache* ) * 10 );

    // Each index is a pointer to struct cache with the malloc size it pointing
    // to equal to struct cache
    c1[0] = (struct cache*) malloc( sizeof(struct cache) );

    // Any later index would have to use malloc or assign a pointer to c1

    c1[0]->s = 1;
    c1[0]->E = 2;
    c1[0]->b = 3;

    printf("%d %d %d", c1[0]->s,
                       c1[0]->E,
                       c1[0]->b );
    return 0;

}
© www.soinside.com 2019 - 2024. All rights reserved.