I am new in C and trying to understand pointers and memory. I would like to create a multidimensional array pointer [][] allocated by calloc
. But I am getting segfault. Can anyone point out what I am doing wrong?
Attempt 1:
struct line {
struct dot *a;
};
struct data {
struct line ***bold;
};
#define COUNT 16
void func (void) {
struct data *data = calloc(1, sizeof(*data));
data->bold = calloc(COUNT * COUNT + 1, 4);
for (size_t i = 0; i < COUNT; i++) {
for (size_t j = 0; j < COUNT; j++) {
data->bold[i][j]->a = i + j; //segfault here
}
}
}
Attempt 2:
struct line {
struct dot **a;
};
struct data {
struct line **bold;
};
void func (void) {
struct data *data = calloc(1, sizeof(*data));
data->bold = calloc(COUNT + 1, 4);
for (size_t i = 0; i < COUNT; i++) {
data->bold[i]->a = calloc(COUNT + 1, 4); //segfault here
}
for (size_t i = 0; i < COUNT; i++) {
for (size_t j = 0; j < COUNT; j++) {
data->bold[i]->a[j] = i + j;
}
}
}
Here, I have tried to create a nested double-pointer allocated by calloc
which I hoped will give me similar data variables as my above attempt. However, it segfaulted as well. Why is this segfault happening and how can I fix this code? My goal is to print something like this below and get an output
printf("%d : %d\n", data->bold[2]->a[3], data->bold[2][3]->a);