Home > Mobile >  Accessing an element in struct holding a pointer to a matrix array
Accessing an element in struct holding a pointer to a matrix array

Time:05-08

I am trying to access an element using temp_param->mat_ptr[0][0] but it produces an error Format specifies type 'int' but the argument has type 'int *'. What is the problem?

#include <stdio.h>

typedef int matrix[4][4];

matrix mat;

typedef struct tnode {
    matrix *mat_ptr;
} params;

params temp_param;

int main() {
    temp_param.mat_ptr = &mat;
    /* temp_param->mat_ptr[0][0] produces an error "Format specifies type 'int' but the argument has type 'int *'" */
    printf("%d", temp_param->mat_ptr[0][0]);

    return 0;
}

CodePudding user response:

The type of expression params.mat_ptr is a pointer to 2D array. Therefore is must be dereferenced before being accessed like 2D array. Moreover temp_param is a struct, not a pointer to struct. Therefore its members are accessed via . operator rather than ->.

Try (*temp_param.mat_ptr)[0][0]

  •  Tags:  
  • c
  • Related