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));