8

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?

1
  • 6
    I think the difference here is what's easier to understand. Commented Oct 20, 2013 at 18:08

3 Answers 3

2

You would have m[x].a[y] which is more complicated syntax than m[x][y] but adds nothing lexically

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.