The difference between memory and efficiency between declaring a normal array and an array declared inside a structure

When declaring arrays in C, they can usually be declared as:

int arr[10] 

or they can also be declared inside a structure such as:

 struct structArr{ int sArr[10]; }s1; 
  • Will there be any compilation of memory or space when using s1.sArr[] instead of arr[] , if so, why?
  • Is one form more efficient and faster than the other?

I personally believe that arr[] will be faster than s1.sArr[] , but I don’t know if I am right or not, but I don’t have a technical answer.

+4
source share
4 answers

The answer to your question depends on the compiler and optimizations.

With a recent GCC compiler with optimizations of at least -O1 arr[] will not be faster than s1.sArr[] . In fact, if for some reason (for example, its other fields) s1 more aligned than arr , then it may happen (due to cache effects) that s1.sArr[] may be slightly better (for example, because it is more aligned cache line size). But really, in terms of performance, using arr[] or s1.sArr[] (almost basically) is the same.

For ease of reading, things can be different. You may want to pack related items into some struct . (And you can avoid too many variable names).

+2
source

I would not expect that there would be any difference, no.

The compiler β€œknows” that the offset of the sArr field from the base address s1 is 0, so I would suggest that access can be made using the same sequence of instructions.

Of course, the array wrapper in the structure allows you to assign and transfer / return it by value, which can be a nice advantage.

+5
source

To add to the other answers, while potential performance and memory differences are negligible at almost any time, using this indirect structure function allows you to determine the size of the array even when passing the function (without decomposing into a pointer). This can be quite helpful.

Consider the following program:

 #include <stdio.h> typedef struct { int arr[10]; } my_arr; void foo1(my_arr arr) { printf("%d\n", sizeof(arr.arr)); } void foo2(int arr[10]) { printf("%d\n", sizeof(arr)); } int main() { my_arr a1; foo1(a1); /* prints 40 on my machine (10*sizeof(int)) */ int a2[10]; foo2(a2); /* prints 8 on my machine (sizeof(int*)) */ } 
+2
source

I don’t think that the difference (if at all) is to lose sleep.

If your example is complete, I would choose int arr[10]; just for readability.

0
source

All Articles