Home > Back-end >  How do I change char from 2D array referenced with pointer of pointer
How do I change char from 2D array referenced with pointer of pointer

Time:10-12

In the bellow example, I would like to change some of the characters of my 2D array using standard "array[x][y]" syntax, I have tried several syntax such has *(world[0][1]), ... but always getting error Syntax or segmentation fault.

char *map[] = { "12345\0",
                "67890\0"
              };

void change( char **world) {

   world[0][1] = 'X';   // <-- I want to replace character 2 of line 1 (2) by char 'X'

}

void main() {

    printf("line=%s\n",map[0]);
    printf("char=%c\n",map[0][1]);
    change(map);
    printf("now line is =%s\n",map[0]);

}

resulting

$ ./a.out
line=12345
line=2
Segmentation fault

Thanks for your help

CodePudding user response:

In C language, 2D arrays and arrays of pointers are different animals.

char *map[] = { "12345\0",
                "67890\0"
              };

declares an array of 2 char pointers, both pointing to non modifiable string literals.

You can initialize non const char arrays from a literal and then use them in your array of pointers:

char arr1[] = "12345\0"; // 7 chars with 2 terminating null characters
char arr2[] = "64789\0"; // id.
char *map[] = {arr1, arr2};

Alternatively, you can declare a true 2D array (all rows have same size) and initialize it:

char map[][7] = {"12345", "6789"};

CodePudding user response:

The Problem

you can't use arr[y][x] syntax, because

void foo(char **bar) {
   (char[H][W)bar; // ILLEGAL
}

is illegal, you can't turn a char ** into a char [][], you either have to use a different syntax or pass map not as a pointer, but as an array(and change the type of map)

SOLUTIONS

What you can do is take map as a char [][]

// note that you have to change from char *map[] to this
char map[H][W] = ...;

map[y][x] = '9';

OR

With a pointer to a multi-dimentional, you can get the element at n, with something like:

#define W 5 // width
#define H 2 // height
char *arr[H][W] = { "1234\0", "5678\0" };

// start is &arr[0][0]
void changeAt(char *start, int n, char x) {
   // treat arr as a 1 dimentional array
   *(start   (n / W)   (n % W)) = x;
}

// start is &arr[0][0]
void changeXY(char *start, int x, int y, char n) {
   *(start   (y / W)   x) = n;
}
  • Related