alex tt
alex tt

Reputation: 1

How to create many blocks of memory with one reference in C

I am trying to allocate blocks of memory for my program. I need to allocate 8 blocks of memory each having 62500bytes ( sizeof Int * 32 ) . In a way I am allocating 2,000,000 bit for each block (total number of blocks are 8).

I tried using int *a= (int*) calloc(62500 * 8, sizeof(int)) and I use

int i=0;
for (i = 0; i < 62500 * 8; i++) {

            blk[i] = i;
        }

I use the above to allocate a value to each address so that it is easy to keep track of which index I need to fetch, since unlike array which are consecutive blocks of memory , if I use calloc I do not get consecutive memory addresses. But my problem here is I want each of 8 blocks allocated with a start index as 0 and end as 62500.Like block1(0...62500) , block2(0...62500),block3(0...62500) ... block8(0...62500). I am not sure how to get this kind of structure.

I started with something like:

typedef struct block { 

int b;      

} blk;

How do I make a struct *blk = {block1,block2,block3...block8}, So that I can reach to each block from pointer *blk.

Thanks

Upvotes: 0

Views: 120

Answers (1)

Aioi Yuuko
Aioi Yuuko

Reputation: 118

Get a pointer to an array of arrays.

#define BLK_SZ 62500
#define BLK_NMEMB 8

The parentheses here denote that blk is a pointer to an array, rather than an array of pointers.

int (*block)[BLK_SZ][BLK_NMEMB] = calloc(62500 * 8, sizeof(int));

Note that the cast is unnecessary because void * is guaranteed to convert to any other pointer type. Now you can address it like:

(*block)[0][9001] = 14;

You can also create a typedef:

typedef int blk[BLK_SZ][BLK_NMEMB];

Which can then be used as:

blk *block = calloc(BLK_SZ * BLK_NMEMB, sizeof(int));

and addressed in the same manner as above.

If you really must, you can do:

typedef struct {
    int block0[BLK_SZ];
    int block1[BLK_SZ];
    int block2[BLK_SZ];
    int block3[BLK_SZ];
    int block4[BLK_SZ];
    int block5[BLK_SZ];
    int block6[BLK_SZ];
    int block7[BLK_SZ];
} blk;

and:

blk *block = calloc(BLK_SZ * BLK_NMEMB, sizeof(int));

accesed by

(*block).block0[9001] = 14;

Upvotes: 2

Related Questions