4

When declaring arrays in C they can be declared normally like:

int arr[10]

or they can also be declared inside a structure like:

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

What I personally think is that arr[] would be faster than s1.sArr[] but I don't know whether I am correct or not moreover I don't have a technical answer for it.

0

4 Answers 4

5

I wouldn't expect there to be any difference, no.

The compiler "knows" that the offset of the sArr field from the base address of s1 is 0, so I would guess that accesses can be done using the exact same sequence of instructions.

Of course, wrapping the array in a structure makes it possible to assign and pass/return it by value, which can be nice benefits.

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

Comments

2

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

With a recent GCC compiler with at least -O1 optimization, arr[] won't be faster than s1.sArr[]. Actually, if for some reason (e.g. its other fields) s1 is more aligned than arr is, then it could happen (because of cache effects) that s1.sArr[] might be slightly better (e.g. because more aligned to cache line size). But really from a performance point of view using arr[] or s1.sArr[] is (nearly mostly) the same.

For readability reasons things can be different. You may want to pack related items into some struct. (And you may want to avoid having too much variable names).

Comments

2

To add to the other answers, while the potential performance and memory differences are negligible almost anytime, using this struct indirection thing allows you to determine the size of the array even when passed to a function (no decay to pointer). This can be quite useful.

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*)) */
}

Comments

0

I dont think the difference (if any at all) is worth losing sleep over.

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

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.