0

I have 2 dimensional array inside structure at file scope. The structure is passed to several functions. I need to allocate this array to match [LINES][COLS]. I would also need to reallocate it if terminal gets resized. What would be best way to implement this?

I found out that i should use pointers instead of arrays inside the struct. But im having problems allocating pointer that should represent 2 dimensional array.

The original structure:

struct data {
    // KB/s
    float rxs;
    float txs;
    // peak KB/s
    float rxmax;
    float txmax;
    float max;
    float max2;
    // total traffic
    int rx;
    int tx;
    int rx2;
    int tx2;
    // packets
    int rxp;
    int txp;
    // bandwidth graph
    float rxgraphs[LEN];
    float txgraphs[LEN];
    bool rxgraph[GRAPHLEN][LEN];
    bool txgraph[GRAPHLEN][LEN];
};

Pointer version that doesnt work:

struct data {
    // KB/s
    double rxs;
    double txs;
    // peak KB/s
    double rxmax;
    double txmax;
    double max;
    double max2;
    // total traffic
    long rx;
    long tx;
    long rx2;
    long tx2;
    // packets
    long rxp;
    long txp;
    // bandwidth graph
    double *rxgraphs;
    double *txgraphs;
    bool **rxgraph;
    bool **txgraph;
};

int main(int argc, char *argv[]) {
    struct data d = {.rxs = 0, .txs = 0};
    d.rxgraphs = malloc(COLS * sizeof(double));
    d.txgraphs = malloc(COLS * sizeof(double));
    d.rxgraph = malloc((LINES/2) * COLS * sizeof(bool));
    d.txgraph = malloc((LINES/2) * COLS * sizeof(bool));
Ari Malinen
  • 576
  • 2
  • 6
  • 20

1 Answers1

1

You can initialize the two dimensional arrays from the pointers to array of pointers with the following function:

int **array_calloc (int rows, int cols)
{
    register int i;
    float **array = malloc (rows * sizeof (*array));

    for (i = 0; i < rows; i++)
    {
        array [i] = calloc (cols, sizeof (**array));
    }
    return array;
}

malloc is used for the pointer to array of pointer, calloc is used for the array of pointers to initialize the values to 0. Above is general to integers, but you can adapt to bool. After adapting for bool you can simply do:

d.rxgraph = array_calloc (rows, cols);
d.txgraph = array_calloc (rows, cols);

You are responsible for freeing d.rxgraph and d.txgraph when done.

alk
  • 69,737
  • 10
  • 105
  • 255
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • @alk, thank you for the typo fix, iterating to an undeclared `m` wouldn't work -- 'twas late. – David C. Rankin Jun 22 '14 at 17:50
  • Thanks for help but i had problems with this solution. I decided it would be easiest to calloc single block and use that as 2D array with pointer arithmetic. – Ari Malinen Jun 22 '14 at 21:41
  • It is always interesting how different settings call for different ways of addressing the same blocks of memory. Good luck with your code. – David C. Rankin Jun 22 '14 at 21:52