hi i'm working on this program that calculates the various calculations of a matrix (eg determinant and trace and stuff) and i want to use an array in a struct to create a matrix.
in my calculations.h header file, i have this:
struct matrices {
int matrix[3][3]; };
in my calculations.c implementation file i have this function that basically creates the matrix after taking integer inputs from the user:
struct matrices creation (int x, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8 ) {
struct matrices mmm = {{x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}};
return mmm;
}
however, i get the error message error: extra brace group at end of initializer
directed to the line struct matrices mmm = {{x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}};
thanks :)
CodePudding user response:
in my calculations.c implementation file i have this function that basically creates the matrix after taking integer inputs from the user:
In general it is not practical to have a separate int
for each position of the matrix. What if it were a 30x30 matrix?
Instead you use indexes to get each value from the user into the desired position.
Your function:
struct matrices creation (
int x, int x1, int x2,
int x3, int x4, int x5,
int x6, int x7, int x8 ) {
struct matrices mmm = {{x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}};
return mmm;
}
just takes 8 int
to stuff into an array and them return a copy of the array, but is the same as
matrix another = { {x1, x2, x3}, {x4, x5, x6}, {x7, x8, x9} };
example
#include<stdio.h>
typedef int matrix[3][3];
int show(matrix);
int main(void)
{
matrix one = {{1,2,3}, { 4,5,6}, { 7,8,9}};
show(one);
int x1,x2,x3,x4,x5,x6,x7,x8,x9;
x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = x9 = 42;
x5 = -4242;
matrix another = { {x1, x2, x3}, {x4, x5, x6}, {x7, x8, x9} };
show(another);
return 0;
}
int show(matrix M)
{
for ( int y=0;y<3;y =1)
{
for( int x = 0;x<3;x =1) printf("m ", M[y][x]);
printf("\n");
}
printf("\n");
return 0;
};
shows
1 2 3
4 5 6
7 8 9
42 42 42
42 -4242 42
42 42 42
CodePudding user response:
It seems there is a type. You mean either the structure struct matrices
or the structure struct matrix
in the declarations of the code snippet.
If to ignore the typo the initialization will look like
struct matrices {
int matrix[3][3]; };
struct matrices creation (int x, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8 ) {
struct matrices mmm =
{
{
{ x, x1, x2 },
{ x3, x4, x5 },
{ x6, x7, x8 }
}
};
return mmm;
}
Or the following way
struct matrices {
int matrix[3][3]; };
struct matrices creation(int x, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8 ) {
struct matrices mmm =
{
.matrix =
{
{x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}
}
};
return mmm;
}
That is the aggregate struct matrix contains a two dimensional array. So you need to use one more pair of braces.