How to speed up dereferencing a pointer?

Here is my code:

#include <stdlib.h> //malloc

#define lineSize 16
#define columnSize 16
#define cellSize 16

int main()
{
    unsigned char*** tab;
    tab = malloc(sizeof(unsigned char**) * lineSize);
    for(unsigned int i = 0; i < lineSize; i++)
        tab[i] = malloc(sizeof(unsigned char*) * columnSize);
    for(unsigned int i = 0; i < lineSize; i++)
        for(unsigned int j = 0; j < columnSize; j++)
            tab[i][j] = malloc(sizeof(unsigned char) * cellSize);


    unsigned int line = 0;
    unsigned int column = 0;
    unsigned int cell = 0;

    unsigned char* ptr = &tab[line][column][cell];

    for(line = 0; line < lineSize; line++)
        for(column = 0; column < columnSize; column++)
            for(cell = 0; cell < cellSize; cell++)
                *ptr = ...;

    return 0;
}

This code fills a tab with values ​​that are known only at runtime.

There are no problems in this case, because lineSize, columnSize and cellSize are small. The problem is that when cellSize becomes 100000+, then dereferencing a pointer becomes expensive in terms of time, so I thought to use a pointer to avoid dereferencing.

The problem is that I don’t know how to do this so that the pointer is updated as a change to a row, column or cell.

Appreciates your help, thanks.

EDIT : further explanation:


lineSize, columnSize cellSize, . , , , - , 16 * 16 * 100000 (When cellSize = 100000).

, - :

tab[2][5][3] = tab + 2*16*100000 + 5*100000 + 3;

​​, 16 * 16 * 100000 .

, , , tab[line][column][cell], , , , cell .

+4
2

, . ptr cell, .

, :

ptr2 = ptr + dist

, , , , . .


:

for(line = 0; line < lineSize; line++) {
    unsigned char** my_line = tab[line];
    for(column = 0; column < columnSize; column++)
        unsigned char* my_col = my_line[column];
        for(cell = 0; cell < cellSize; cell++)
            unsigned char data = my_col[cell];
+3

UB .

tab[line][column][cell]; 

malloc-ed. , , . .

-1

Source: https://habr.com/ru/post/1684541/


All Articles