decentProgrammer
decentProgrammer

Reputation: 21

Why am I getting Segmentation fault for using array of char pointers?

I'm trying to play around with c and pointers since I'm new to the language but I'm not sure why I'm getting a segmentation fault, when I have initialized everything to null then going to re-write the array of char pointers? Can someone explain what I did wrong?

#define MAX_SIZE 70    
void gridTest(char*[]);

int main()
{
    char *grid[MAX_SIZE] = {0};
    testGrid(grid);
    return 0;
}    

void testGrid(char *grid[]){
    for(int i=0;i<MAX_SIZE;i++){
        *grid[i] = ' ';
    }
    for(int j=0;j<MAX_SIZE;j++){          
        printf("The Character is space, test: %c",*grid[j],j);
    }
}

ERROR

Segmentation fault: 11

Upvotes: 0

Views: 62

Answers (2)

legoscia
legoscia

Reputation: 41648

By declaring an array of char pointers, you become responsible for making those pointers point to something. If you just want to get a 70x70 grid, you can get around that by declaring grid as an array of char arrays:

char grid[MAX_SIZE][MAX_SIZE];

That way, the memory is automatically allocated and ready for use.

*grid[i] is equivalent to grid[i][0], so testGrid currently accesses only the first column in each row. To access all cells in the grid, you could use two nested for loops and access them with grid[i][j] or similar.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

Check this line

  *grid[i] = ' ';

you are trying to store the space character in a memory pointed to by grid[i], that's cool, but where does that one point to?

Answer is: Invalid memory (a null pointer, it is). The memory address you're trying to use is invalid and attempt to deference it invokes undefined behavior.

That being said, seeing your usage, you don't need an array of char pointers, an array of char would suffice. Change your array definition to

 char grid[MAX_SIZE] = {0};

and change the called function as

void testGrid(char grid[]){

        for(int i=0;i<MAX_SIZE;i++){
              grid[i] = ' ';
         }
        for(int j=0;j<MAX_SIZE;j++){
           printf("The Character is space, test: %c",grid[j],j);
        }
 }

Upvotes: 2

Related Questions