user1323328
user1323328

Reputation: 119

segmentation fault when writing to a char to a char array

I am writing a code to processing a 2-d char array.

char *board[] = {"aa"};

I pass the array to a function

 search(board, row, col);
 ..........
 bool search(char** boards, int row, int col)
 {
      // Inside the function, I want to modify the boards[x][y] 
      // from the board within x and y, x < row, y < col
      // I get the segmentation fault here because the boards is 
      // allocated to the static memory and cannot be changed.
      boards[x][y] = 'c';
 }

In C++, I can use

 vector< vector<char> boards

to change the elements in the specific location. But in C, there is no vector.

Is anyone has good advice about how to modify the boards 2-D array? Thanks.

Upvotes: 0

Views: 325

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

In C you can use for example Variable Length Arrays if the compiler supports them.

For example

int size_t m = 2;
int size_t n = 3;
char board[m][n] = { "aa", "bb" };

search( m, n, board );

// Add more search code here...

bool search( size_t rows, size_t cols,  char board[][cols] );

Another approach is to use an arrays of pointers where each pointer points to a dynamically allocated array or the array itself can be dynamically allocated. For example

int size_t m = 2;
int size_t n = 3;

char **board;

board = malloc( m * sizeof( char * ) );
for ( size_t i = 0; i < m; i++ ) board[i] = malloc( n * sizeof( char ) );
strcpy( board[0], "aa" );
strcpy( board[1], "bb" );

search( board, m, n );

//,,,

bool search( char **board, size_t rows, size_t cols );

In this case you have to free the allocated memory when array will not be needed any more.

As for the segmentation fault you got then you are trying to change a string literal. They are immutable. Any attempt to modify a string literal results in undefined behaviour.

Upvotes: 1

papalmac
papalmac

Reputation: 5

Try declaring board as 2D array, char board[10][10]

Also change the search function declaration to use board as a 2D array like:

Search(char board[][], int x, int y) {...

I think that your code is fails because you mix arrays of pointers with an argument which expect a pointer pointer to char.

Regards

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726659

The problem is that you are making an array of pointers, and set the pointers to ppint to string constants. Memory of string constants is not modifiable, so writing to it causes segmentation fault.

Changing an array of pointers to 2D array of characters will fix this problem

char board[][10] = {"aa", "bb"};

Upvotes: 4

Related Questions