Isn't double[][] equivalent to **double?

前端 未结 9 1464
心在旅途
心在旅途 2020-12-29 02:37

I\'m asking this because my program have two functions to multiply matrices, they multiply only 4x4 and 4x1 matrices. The headers are:

 double** mult4x1(doub         


        
9条回答
  •  再見小時候
    2020-12-29 03:05

    No... m1 is an array with four elements, each of which is an array of four elements. Same with m2. Even if the first "level" decays from an array into a pointer, the second "level" won't. The question is why? Let's look at some code:

    /* double[4][4] implicitly converts to double(*)[4]
     * giving you a pointer to first element of m1 so
     * you get back an array of four doubles.
     */
    double (*pm1a)[4] = m1[0];
    
    /* This isn't right, but let's pretend that it was
     * and that what you got back was a pointer
     * to a pointer that pointed to m1 properly.
     */
    double **pm1b = (double **)m1[0];
    

    So, what would happen with our hypothetical code if we were to do pm1a[1] and pm1b[1]?

    pm1a[1] is fine: it would correctly advance pm1a by 4 * sizeof(double) (since the pointer points to double[4]).

    pm1b[1], on the other hand, would break: it would advance by the wrong amount: the size of a pointer to a double.

    But this isn't all. There's a more subtle bug still. If both dimensions were to decay, the compiler could not know that an array is being accessed. It will happily interpret pm1b[1] as a pointer to a double. And then what happens? It will take whatever double value is stored at that location and treat it as a pointer to a double.

    You can see why this would be a disaster.

提交回复
热议问题