1

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);
blackbeard
  • 385
  • 2
  • 12
  • Please do a search on "allocate 2D array". This is covered many many times including why your allocations are not correct and what the correct way is. – kaylum Feb 26 '20 at 02:29
  • 1
    @kaylum Thanks, it does provide an elaborate explanation. And my code follows the suggested practice. However, I am still getting a segfault. Perhaps your seasoned eye will be able to catch what is going wrong? – blackbeard Feb 26 '20 at 03:14
  • Consider this line: `data->bold = calloc(COUNT * COUNT + 1, 4);`, what makes you think that `sizeof(*data->bold) == 4`? Why is there a plus one? Also note that `calloc` may not be a portable way to ensure that those pointers are nullified. – Bob__ Feb 26 '20 at 07:28

0 Answers0