1

I'm trying to address matrix of struct, but some goes wrong. This the code:

typedef struct {
    bool state;
    float val;
    char ch[11];
} st_t;

st_t matrix[3][5];


int main(int argc, char *argv[])
{
    int i, j;

    // Init matrix value matrix[i][j] = i.j
    ....

    // Init matrix pointer
    st_t (*pMatrix)[3][5];
    pMatrix = &matrix;

    // print address element
    fprintf(stderr, "\n\nsizeof st_t:%d\n\n", sizeof(st_t) );
    for( i = 0; i < 3; i++ )
    {
        for( j = 0; j < 5; j++ )
            fprintf(stderr, "matrix[%d][%d] ADDR:%p    pMatrix[%d][%d] ADDR:%p\n", i, j, &(matrix[i][j]), i, j, &pMatrix[i][j]);
        fprintf(stderr, "\n");
    }
    return 0;
}

This is the output of code:

sizeof st_t:16

matrix[0][0] ADDR:0x8049a00             pMatrix[0][0] ADDR:0x8049a00
matrix[0][1] ADDR:0x8049a10             pMatrix[0][1] ADDR:0x8049a50
matrix[0][2] ADDR:0x8049a20             pMatrix[0][2] ADDR:0x8049aa0
matrix[0][3] ADDR:0x8049a30             pMatrix[0][3] ADDR:0x8049af0
matrix[0][4] ADDR:0x8049a40             pMatrix[0][4] ADDR:0x8049b40

matrix[1][0] ADDR:0x8049a50             pMatrix[1][0] ADDR:0x8049af0

For example why does pMatrix[0][1] is different from address of matrix[0][1]?

Thanks in advance.

1 Answer 1

2

You have declared pMatrix to be a pointer to a 3⨉5 matrix of st_t, that is, it points to an array of 3 arrays of 5 st_t objects. Given this, pMatrix[0] is an array of 3 arrays of 5 st_t objects. However, since it is an array, it is automatically converted to a pointer to the first element of the array. So it becomes a pointer to an array of 5 st_t objects.

Then pMatrix[0][0], pMatrix[0][1], pMatrix[0][2], and so on are successive arrays of 5 st_t objects, not successive st_t objects.

Most likely, what you want is:

// Declare pMatrix to be a pointer to an array of 5 st_t objects,
// and point it to the first row of matrix.
st_t (*pMatrix)[5] = matrix;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, pMatrix[0] is a POINTER to array of 5 element. pMatrix[0][0] is THE array and pMatrix[0][0][2] is the third element of the array. We can also write (*pMatrix)[0][2] for the same element.
+1 to the answer. @GMERiello dont understand what you mean by the comment but the answer seems correct. Is this what you wanted or not?
@eznme yes, the answer helped me, I want to access to a single element of the matrix through the pointer pMatrix. Now pMatrix[0][1] is not a st_t element but a complete row. pMatrix[0][1][2] is the third element of second row, but also (*pMatrix)[1][2], in other word (obvious) pMatrix[0] == (*pMatrix). I hope now is more clear.

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.