I am new to C language, so my question may not meet high standards
can we use
struct mat{
int a[10];
};m[10];
instead of
int mat[10][10];
whats the difference? and which is more efficient?
I am new to C language, so my question may not meet high standards
can we use
struct mat{
int a[10];
};m[10];
instead of
int mat[10][10];
whats the difference? and which is more efficient?
You should trust the compiler with that. However, I may suggest 2 alternatives that I know works well depending on your application.
1) use int a[10][10] but make sure you access them in the proper order when looping. The compiler will "underneath" use a single array structure so acessing in order
for( i = 0 ; i < 10 ; i++) {
for (j = 0 ; j < 10 ; j++) {
// do something with a[i][j]
}
}
vs
for( i = 0 ; i < 10 ; i++) {
for (j = 0 ; j < 10 ; j++) {
// do something with a[j][i]
}
}
is different in terms of performance. The later is more performant.
2) The option 1 requires extra care and is counter-intuitive. I much prefer to do
int a[100]
and do
for( i = 0 ; i < 100 ; i++)
inline_function(a[i]);
where the function should be declared inline and preform the thing you have to have done. If you can avoid the function, it's even better. For example, if it's a sum, having it 2d or vector doesn't change anything.
EDIT: here is a reference that explain in the details the bit about the array order: http://www.cplusplus.com/doc/tutorial/arrays/
No. This is a struct which contains an array.
struct mat
{
int a[10];
};
You can define an array of struct:
struct mat m[10];
To do it in one step:
struct mat{
int a[10];
}m[10];
Note that you have an extra semicolon before m[10] which isn't correct syntax.
To access an element in arr, you use m[i].a[j]
This is not equivalent in syntax to a 2d array like:
int mat[10][10];
which you can access using mat[i][j]