3

I want to have a struct with multiple 3x3 arrays within each object, and so I want to create a generic pointer to point to any one of these arrays within a particular object. This is what I did, but it keeps telling me that the pointer types are incompatible. How should I fix my array_ptr?

typedef struct my_struct{

    char array[3][3];

} object;

object* init_obj(){

    object* platinum = (object*)malloc(sizeof(object));

    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            platinum->array[i][j] = 'w';
    return platinum;
}

int main(){

    object* platinum = init_obj();

    char **array_ptr = platinum->array;

    printf("%c\n", array_ptr[0][0]);

    return 0;
}

The specific warning is the following:

warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
  char **array_ptr = platinum->array;

When it runs, it seg faults, but it wouldn't if I printed straight from platinum->array. How do I fix this?

P.P
  • 117,907
  • 20
  • 175
  • 238

1 Answers1

2

The types are indeed incompatible, indeed. The array platinum->array gets converted into a pointer to its first element when assigning, and its type is char(*)[3]. But you are assigning it to char**.

You want:

char (*array_ptr)[3] = platinum->array;

Related: What is array decaying?

P.P
  • 117,907
  • 20
  • 175
  • 238