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?
Structure can be defined as a data structure used as container which can hold variables of different types. On other hand Array is a type of data structure used as container which can hold variables of same type and do not support multiple data type variables.
An array of structures is simply an array in which each element is a structure of the same type. The referencing and subscripting of these arrays (also called structure arrays) follow the same rules as simple arrays.
A two-dimensional array is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and columns. Many games use two dimensional arrays to plot the visual environment of a game.
You would have m[x].a[y]
which is more complicated syntax than m[x][y]
but adds nothing lexically
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With