0

i am trying to create array of structure. Method i was using for creating array of structure which was working fine in Linux and Mac but this is throwing error in windows

uint32_t size;
Test TestArray[size];
TestArray[i] = Test;
//i

Error I am getting in windows

error C2131: expression did not evaluate to a constant 

I have also tried

typedef struct Test {
    char *x;
    char *y;
} Test;

uint32_t size;
status = napi_get_array_length(env,args[2],&size);
assert(status == napi_ok);

struct Test  testList[size];
napi_value SharePrefixObject;
for(uint32_t i=0;i<size;i++){
Test t;
testList[i]= t;

Question How can resolve above error ?

Shivam Kumar
  • 123
  • 3
  • 10
  • 4
    C++ arrays have to be constant sized. Variable length arrays only work because of non-standard compiler extensions so they aren't portable. – eesiraed Apr 08 '20 at 05:46
  • Related if not the duplicate: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Apr 08 '20 at 05:54
  • ***Question How can resolve above error ?*** use a `std::vector` instead which is proper standard `c++` – drescherjm Apr 08 '20 at 05:55
  • `typedef struct Test` in `c++` you don't need the `typedef` – drescherjm Apr 08 '20 at 05:56
  • `uint32_t size; Test TestArray[size];` should be illegal on all systems or at least its Undefined Behavior on the compilers that support the non-standard VLA extension in `c++`. It's undefined behavior because `size` was not initialized before this. And if this was in the global scope an array of size 0 that can not be enlarged is not so useful. – drescherjm Apr 08 '20 at 05:58

2 Answers2

2

There are no variable length arrays in C++. The C++ way to do this is to use a vector.

Your code is very C like. The way you declare structs looks like C. The way you use pointers is idiomatically like C. Anyway, if you want to do some proper C++ programming then do this

#include <vector>

std::vector<Test> testList(size);
john
  • 85,011
  • 4
  • 57
  • 81
-1

You need to use constant for array size like:

Test TestArray[123]; //were 123 - max size of your's array data

or

#define TEST_ARRAY_SIZE 123

Test TestArray[TEST_ARRAY_SIZE];

if you need different size use something like mallok:

uint32_t size;
Test *TestArrayPnt;

//some ware you got a size like size = 123

TestArrayPnt = new Test[size];

//continue a program. You can use TestArrayPnt [111] were 111 some offset less than size

delete[] TestArrayPnt; //when finish
Vladimir
  • 109
  • 1
  • 2