5

Probably this is very dumb question. I'm very new to C. Could anyone please explain in simpler way why empty array has 0 byte in memory?

int shoot = 2;    // 4 bytes
int zet[4] = {};  // 16 bytes
int raw[] = {};   // 0 bytes

Why variable raw takes 0 bytes from memory?

9
  • Why would you expect it not to? Commented Jul 12, 2021 at 3:14
  • 2
    int raw[] = {}; is equivalent to int raw[0];. The number of bytes in an int array of length n is n * sizeof(int). So for an empty array, the number of bytes is 0 * sizeof(int), which is zero. Note that zero-sized arrays are a C extension. Commented Jul 12, 2021 at 3:18
  • Here's another way to understand it. Suppose something is zero feet long. What is its length in inches? It's 0 * 12, which is zero inches. If you prefer metric, suppose something is zero meters long. What is its length in centimeters? It's 0 * 100, which is zero centimeters. Commented Jul 12, 2021 at 3:25
  • 3
    int raw[] = {}; --> invalid C. Commented Jul 12, 2021 at 3:25
  • 1
    @TomKarzes Post not tagged as gcc. Default, it is not allowed in C. Sure other languages or extensions can do what they will. Commented Jul 12, 2021 at 3:28

1 Answer 1

2

When you declare zet, you give the array a size. When you declare raw, you do not. When an array is declared with empty square braces, the size allocated for it by the compiler is determined by the number of elements in the initializer.

From a 2007 committee draft of the C standard:

EXAMPLE 2 The declaration int x[] = { 1, 3, 5 }; defines and initializes x as a one-dimensional array object that has three elements, as no size was specified and there are three initializers.

In your case, you have int raw[] = {}; There are no initializers, so the array has no elements, and thus is of zero size.

Zero size arrays, however, are not necessarily portable, as they are not part of the C standard. This is compiler-dependent language extension.

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

1 Comment

Further to this, we can infer that the compiler is for a 32bit system from int shoot taking 4 bytes. Therefore an array with 4 elements equals 16 bytes in size

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.