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?

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.