2

I'm creating a set of functions that takes a pointer to a 2D-Array and fills the array with some data

This is how I got it right now:

17 void m4identity(float *m[4][4]) {
18    *m = (float[4][4]) { { 1, 0, 0, 0 },
19                         { 0, 1, 0, 0 },
20                         { 0, 0, 1, 0 },
21                         { 0, 0, 0, 1 } };
22 }

But unfortunately I get a compiler error:

linalg.c:18:7: error: incompatible types when assigning to type ‘float *[4]’ from type ‘float (*)[4]’

Questions:

  1. What is the difference between (*)[4] and *[4]?

  2. Is there a better way to do this?

    I initially tried to return a pointer to the array created inside the function but this threw another compiler error because it would be out of scope. I also want to avoid allocating space for the array from within the function as that would be hard to control.

1 Answer 1

1

What is the difference between (*)[4] and *[4]?

The [] declaration specifier has higher precedence, so float *arr[4] declares an array of 4 pointers-to-float, while float (*arr)[4] declares a pointer-to-array-of-4-float.

Is there a better way to do this?

Just let the array decay into a pointer and use assignments:

void m4identity(float m[4][4])
{
    memset(m, 0, 4 * sizeof(m[0]));
    for (int i = 0; i < 4; i++) {
        m[i][i] = 1;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

note that this is exactly the same as declaring void m4identity(float (*m)[4])

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.