Too many initializations for Union Structure array

This code is intended to test my knowledge of accessing the structure of an array. When I executed this code, it gave me an error two many initializations for the parameter. Please help me understand the error and fix this problem. I tried to reuse code that is already resolved by someone. My question is about populating Struct with Param_u param parameters

#include <iostream> #include <stdio.h> #include <string.h> #define ARRAY_COUNT(arr) (sizeof (arr) / sizeof *(arr)) typedef union { struct { // Function parameters int *array; size_t size; }; struct { // Function return value float mean; int Median; }; } Param_u; int main() { int array_1[] = {1, 2, 3, 4, 5}; int ret1, ret2; // Fill the Struct with parameters Param_u param = { .array = array_1, .size = ARRAY_COUNT(array_1), }; return 0; } 
+5
source share
1 answer

This is not standard C ++. You use an anonymous struct and assigned initializers (function C99). C ++ does not support this. Enable the -pedantic-errors option on clang ++ and g++ . See this for more details. You use compiler extensions so that your program is not portable.

See the demo here .

clang++ gives the following diagnostics:

 Error(s): source_file.cpp:12:5: error: anonymous structs are a GNU extension [-Werror,-Wgnu-anonymous-struct] struct { // Function parameters ^ source_file.cpp:16:5: error: anonymous structs are a GNU extension [-Werror,-Wgnu-anonymous-struct] struct { // Function return value ^ source_file.cpp:28:9: error: designated initializers are a C99 feature [-Werror,-Wc99-extensions] .array = array_1, ^~~~~~~~~~~~~~~~ source_file.cpp:29:9: error: designated initializers are a C99 feature [-Werror,-Wc99-extensions] .size = ARRAY_COUNT(array_1), ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ source_file.cpp:24:16: warning: unused variable 'ret2' [-Wunused-variable] int ret1, ret2; ^ source_file.cpp:27:13: warning: unused variable 'param' [-Wunused-variable] Param_u param = { ^ source_file.cpp:24:10: warning: unused variable 'ret1' [-Wunused-variable] int ret1, ret2; ^ 3 warnings and 4 errors generated. 
0
source

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


All Articles