Array Initialization [c / C ++]

Why is this not allowed?

#include <cstdio> struct Foo { int fooId; char arr[ ]; } fooList[] = { {1, {'a', 'b'}}, {2, {'c', 'd'}} }; int main() { for (int i = 0; i < 2; i++) printf("%d %c\n", fooList[i].fooId, fooList[i].arr[0]); } 

whereas it is allowed:

 struct Foo { int fooId; char arr[2]; // this line modified } fooList[] = { {1, {'a', 'b'}}, {2, {'c', 'd'}} }; 
+4
source share
3 answers

Only the last element of the C structure can be flexible, as in arr[] .

Shameless copying from clause 6.7.2.1, clause 16 of ISO C99:

16 As a special case, the last element of the structure with more than one named member may have an incomplete array type; this is called a flexible array element. With two exceptions, the flexible array element is ignored. Firstly, the size of the structure must be equal to the offset of the last element of the identical structure, which replaces the flexible element of the array with an array of undefined length .106) ...

EDIT:

As for C ++, see this . Bottom line: elements of a flexible array are generally not allowed in C ++ - at least for now.

+15
source

In C ++, all members of a user type must have full types, and the arr member does not have a full type unless you give it a size.

In C, the structure definition will be compiled, but you may not get what you want. The problem is that an array without size is allowed at the end of the structure, which will be used as a proxy to access the contiguous block of memory after the instance. This allows you to implement a mute vector:

 typedef struct vector { int size; char buffer[]; } vector; vector* create_vector( int size ) { vector* p = (vector*) malloc( sizeof *p + size ); // manually allocate "size" extra p->size = size; }; int main() { vector* v = create_vector(10); for ( int i = 0; i < v->size; ++i ) printf("%d\n", v->buffer[i] ); free(v); } 

But the language does not allow you to initialize curly braces, since the compiler does not know how much memory needs to be held (in general, in some cases it can know). A member of a structure that does not have a size is only a way of accessing outside the object; it does not save memory by itself:

 printf( "sizeof(vector)=%d\n", sizeof(vector) ); // == sizeof(int) 
+1
source

In C ++ 03, this is unacceptable in a structure or class!

The Comeau C ++ compiler gives this error:

  "ComeauTest.c", line 3: error:  
 incomplete type is not allowed 
       char arr [];
            ^ 

Exactly similar question yesterday: Difference between int * and int [] in C ++

0
source

Source: https://habr.com/ru/post/1337941/


All Articles