1

I am trying to set up a 10x10 grid filled with '$' characters and then print it.

    char **plot;
    plot = (char**)calloc(100, sizeof(char));

    int i,j;

    for (i=0; i< 10; i++) {
            for(j=0; j<10; j++){
                    plot[i][j] = '$';
            }
    }

    for (i=0; i<10; i++) {
            for(j=0; j<10; j++) {
                    printf("%c", plot[i][j]);
            }
    }

    free(plot);

This is my code so far, when I run this I get a segmentation fault.

Thomas
  • 43
  • 6
  • This is a 2d array of 100 chars. Have you allocated memory for each row? Also, is your type of `plot` `char` or is it `char *`? – ggorlen Nov 16 '19 at 19:51
  • @ggorlen not sure what you mean. is it not possible to allocate a 2D array with one calloc? – Thomas Nov 16 '19 at 19:54
  • You need a `malloc(sizeof(char *) * 10)` for the row pointers, then 10 `char`s for each row. That should be 11 `malloc`s total. This code only asks for 10 bytes of memory (`sizeof(char)` is guaranteed to be 1). – ggorlen Nov 16 '19 at 19:56
  • One line: `char (*plot)[10] = malloc(10 * sizeof *plot);`, then lose the ensuing calloc entirely. – WhozCraig Nov 16 '19 at 20:07

1 Answers1

5

You have only allocated a list of pointers (and incorrectly)! The line:

plot = calloc(10, sizeof(char*)); // Note the extra * in sizeof(char*)

Creates a 1-dimensional array (list) of 10 pointers. What you then need to do is allocate each of these pointers a buffer of 10 characters:

for (i = 0; i < 10; ++i)
    plot[i] = malloc(10 * sizeof(char)); // Here use "sizeof(char)" but it's always "1"

And, don't forget to call free for each of the calls to calloc and malloc when you're done with the buffers!

Also, you needn't call calloc - you could just use malloc(10 * sizeof(char*)): there's really no point setting all the pointers to zero when you're immediately going to replace them all with what the 'other' malloc calls will return.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 1
    @ggorlen I left the original `calloc` because that what the OP used; in the `malloc` call in my code, I included the `* sizeof(char)` to highlight the difference between this and the `sizeof(char*)` in the first call. But you're right, of course! – Adrian Mole Nov 16 '19 at 19:59
  • @WhozCraig OP doesn't want 10 ***strings*** but a grid of 10 x 10 ***characters***. – Adrian Mole Nov 16 '19 at 20:04
  • =P too much scotch last night (honestly, there is such a thing =P) – WhozCraig Nov 16 '19 at 20:05
  • 2
    Alternately, keep the `calloc` of 100 items, but cast it to `char(*)[10]`, using `char(*plot)[10] = calloc(100, sizeof(char));`. Then the `plot[i][j]` work as intended and access items in the 2D array. – tmlen Nov 16 '19 at 20:10