Strange warning in a C function const multidimensional-array argument

前端 未结 6 1870
长发绾君心
长发绾君心 2020-11-29 11:43

I\'m getting some strange warnings about this code:

typedef double mat4[4][4];

void mprod4(mat4 r, const mat4 a, const mat4 b)
{
/* yes, function is empty *         


        
6条回答
  •  独厮守ぢ
    2020-11-29 12:19

    Here's a problem (IMHO): double[4][4] in a function signature.

    You know it's a double[4][4], but the compiler sees double(*)[4] in the function paramter list, which notably has no array size constraint. It turns your 2D array of 4 by 4 objects into a pointer to a 1D array of 4 objects, and the pointer can be validly indexed as if it were an array of 4 objects.

    I would pass all mat4 objects by pointer:

    void mprod4(mat4 *r, const mat4 *a, const mat4 *b);
    // and, if you don't want to hairy your syntax
    #define mprod4(r, a, b) (mprod4)(&r, (const mat4 *)&a, (const mat4 *)&b)
    

    This will (I believe) ensure const correctness and array size correctness. It may make mprod4 a bit harder to write, and still involves some hairy casts, but it'll (IMHO) be worth it (especially after the macro above):

    void mprod4(mat4 *r, const mat4 *a, const mat4 *b)
    {
        // all indexing of the matricies must be done after dereference
        for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++)
          {
            (*r)[i][j] = (*a)[i][j] * (*b)[i][j];
            // you could make it easier on yourself if you like:
            #define idx(a, i, j) ((*a)[i][j])
            idx(r, i, j) = idx(a, i, j) * idx(b, i, j)
          }
    }
    

    It may look a bit bad when you write it, but I think it'll be cleaner type-wise. (Maybe I've been thinking C++ too much...)

提交回复
热议问题