'Why is pointer of 2d matrix different once using structure?

I'm getting the same memory allocations for the first 2 printf's but the third returns different ones. Can you help me figure out why? Aren't they supposed to be the same?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 4

int main()
{
    
    typedef float mat [SIZE][SIZE];

    mat MAT_A,MAT_B,MAT_C,MAT_D,MAT_E,MAT_F;

    /*Used for going over MATs*/

    struct {
        char *name;
        mat *matrix;
    } mats[]={{"MAT_A",&MAT_A},
          {"MAT_B",&MAT_B},
          {"MAT_C",&MAT_C},
          {"MAT_D",&MAT_D},
          {"MAT_E",&MAT_E},
          {"MAT_F",&MAT_F},
          {"#",NULL}};

    printf("\n%p,%p",&MAT_A,mats[0].matrix[0][0]);
    printf("\n%p,%p",&MAT_A[0],mats[0].matrix[0]);
    printf("\n%p,%p",&MAT_A[1][0],mats[0].matrix[1][0]);
}

Here are the outputs:

enter image description here



Solution 1:[1]

Your member variable matrix is a float (*)[4][4], i.e. a pointer to an array of 4 times 4 float elements. When you deference, say, mat[0].matrix you get a l-value reference to MAT_A, which you can then use to access MAT_A's r-th row and c-th column like this:

(*mat[0].matrix)[r][c]

In C and C++, given a pointer p, accessing its i-th element through the index operator (i.e. p[i]) is the same as deferencing the i-th element after p (i.e. *(p + i)). So, back to your code:

  • mats[0].matrix[0] is the same as *mats[0].matrix;
  • and mats[0].matrix[1] is the same as *(mats[0].matrix + 1), which is undefined behavior.

If you want to print out the address of element (1,0) of MAT_A and the address of the second row of the array pointed to by mats[0].matrix, you may do it like this

printf("\n%p,%p", &MAT_A[1][0], mats[0].matrix[0][1])

or:

printf("\n%p,%p", &MAT_A[1][0], (*mats[0].matrix)[1]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1