2

I am new to C programming and in the development of this exercise I encountered this error that I cannot resolve:

Fields must have a constant size: 'variable length array in structure' extension will never be supported

#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char * argv[]) {
    int nChapters = 2;
    
    typedef struct {
        char title[50];
        char author[50];
    } Heading;
    
    typedef struct {
        char title[50];
        int number_pages;
    } Chapter;
    
    typedef struct {
        Heading heading;
        Chapter chapters[nChapters]; //Fields must have a constant size: 'variable length array in structure' extension will never be supported
    } Book;
    
    printf("\n");
    system("read -p 'Press enter to continue...' ");
    printf("Hello, World!\n");
    return 0;
}

If I replace chapters[nChapters] with an int like chapters[2], program run without problems. Thanks in advance!

GSerg
  • 76,472
  • 17
  • 159
  • 346
LAlchimista
  • 53
  • 1
  • 1
  • 4
  • 2
    The error message really says it all. `nChapters` is a *variable*, not a compile-time constant. And arrays in structures can only use a compile-time constant, like the actual literal integer `2`. This is one of the few reasons to use macros in C. As in `#define NCHAPTERS 2` – Some programmer dude Oct 18 '21 at 07:04
  • Does this answer your question? [Can we have a struct element of type Variable length array?](https://stackoverflow.com/questions/32311269/can-we-have-a-struct-element-of-type-variable-length-array) – GSerg Oct 18 '21 at 07:05
  • You should declare `Chapter chapters` as a pointer and then allocate memory dynamically – Leonardo Araujo Oct 18 '21 at 07:09
  • 1
    Why does it work in one of the online compilers? onlinegdb.com, I am using Xcode – LAlchimista Oct 18 '21 at 07:11
  • Does this answer your question? [Can a const variable be used to declare the size of an array in C?](https://stackoverflow.com/questions/18848537/can-a-const-variable-be-used-to-declare-the-size-of-an-array-in-c) – JHBonarius Oct 18 '21 at 07:15
  • There is a Variable Length Array extension to C which supports the code you have written. Some compilers choose not to implement it. This is pointed to by the error message you are getting. – Zdeněk Jelínek Oct 18 '21 at 07:16
  • It "works" in online compilers, because they use a compiler extension, only available on some compilers (e.g. GCC on Linux). Variable length arrays are "optional" since C11, so they're not supported by all compilers. Prefer not to use them. – JHBonarius Oct 18 '21 at 07:18
  • 1
    Also make sure you don't compile as C++. In C++, `const int` is considered an integer constant expression, but not in C. Overall, C++ is far more flexible with various constant expressions and forms of variable initialization. – Lundin Oct 18 '21 at 07:41
  • Why CLANG uses the keyword "never" in the warning? Is there any fundamental reason why this GCC extension is never going to be implemented by CLANG team? – tstanisl Oct 18 '21 at 08:57

4 Answers4

2

In C you have to declare arrays using a fixed length, your nChapters variable is indeed, a variable. You can turn it into a constant variable by simply adding the const keyword:

const int nChapters = 2
  • Why does it work in one of the online compilers? onlinegdb.com, I am using Xcode – LAlchimista Oct 18 '21 at 07:12
  • 1
    I upvoted your answer, but I think it should be remarked that your first sentence is not necessarily true. There is the concept of [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array), although not universally supported. – frippe Oct 18 '21 at 07:15
  • Defining a variable with `const` does not make it a constant in C for purposes of array declarations. (It might in C++.) – Eric Postpischil Oct 19 '21 at 07:17
1

You can use the preprocessor directive #define:

#define nChapters 2
0

The issue is that you are assuming that it is obvious

Chapter chapters[nChapters];

that value of nChapters is 2. It works that way for a array which is not within a struct or a union. This is supported by weird, non-standard, non-GCC (but accepted as an extension by GCC in C90 onwards), not recommended feature called as VLA or Variable Length Arrays. Using these, one can allocate a auto class array.

Referring to GNU/GCC documentation, section 6.20, It is trivial to note that,

The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

C99 recommends a better way to deal with this requirement - by using flexible length array.

§6.7.2.1 Structure and union specifiers ¶18 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

So, that would change your struct to:

typedef struct {
    Heading heading;
    Chapter chapters[]; 
} Book;

And then allocate the memory dynamically from heap - using malloc.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
WedaPashi
  • 3,561
  • 26
  • 42
  • 1
    Given that this is a beginner, dynamic memory and flexible array members might be beyond them, for now. – Lundin Oct 18 '21 at 07:39
  • I am still immature to use malloc but your answer was very thorough. Thank you! – LAlchimista Oct 18 '21 at 07:42
  • 1
    @LAlchimista: No worries. There are many questions related to malloc and using it with structs in C. The best point to start with malloc is -- https://man7.org/linux/man-pages/man3/realloc.3.html – WedaPashi Oct 18 '21 at 07:49
  • Variable length arrays are not non-standard (the C standard specifies them), not non-GCC (GCC supports them), not not recommended, and not weird. – Eric Postpischil Oct 19 '21 at 10:38
-1

The size of the array member of the struct has to be a constant expression (skip "flexible member" case and GCC's VLA-in-struct extension).

In the C standard the only portable way to have a true named integer constant is using enums. Just replace:

int nChapters = 2;

with this:

enum { nChapters = 2 };
tstanisl
  • 13,520
  • 2
  • 25
  • 40