简体   繁体   中英

SegFault when setting up 2D character array in C

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM