I am getting a syntax error when trying to allocate space for a multidimensional matrix. I am new to coding in C, so anything will help. The error occurs when trying to access the matrix structure elements in the read_matrix function. The syntax error is "expression must have struct or union type". Where the error is produced is commented out in the read_matrix function.
typedef struct {
int *elements;
int rows;
int columns;
} matrix;
void main() {
matrix a, b, c;
void read_matrix(matrix *);
void deallocate(matrix *);
void print(matrix);
matrix add(matrix, matrix);
matrix subtract(matrix, matrix);
matrix multiply(matrix, matrix);
read_matrix(&a);
read_matrix(&b);
c = add(a, b);
deallocate(&c);
c = subtract(a, b);
deallocate(&c);
c = multiply(a, b);
}
void read_matrix(matrix *z) {
int d1, d2, i, x, y, val;
printf("What is the first dimension of the array? ");
scanf("%d", &d1);
printf("What is the second dimension of the array? ");
scanf("%d", &d2);
*z.elements = (int *)calloc(d2, sizeof(int));
*z.rows = d1;
*z.columns = d2;
/* error here. It isn't letting me access the
elements/rows/columns of the matrix */
/* additional code below here */
}
Operator .
has higher precedence than unary operator *
, which means that if you want to access struct members through a pointer z
using *
-and- .
combination, you have to use parentheses. It your case it should be
(*z).elements = ...
Alternatively you can use ->
operator
z->elements = ...
And it is supposed to be int main()
, not void main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.