0

When using C++, I happened to find that I can initialize an array which size is determined by the integer I input when running. I heard that C99 allows that. In compilation, it doesn't determine the size of the array. It realocate the memory in stack to the array in run. I want to find how it is implemented. I also heard that C allows that. It is also a example that C++ cannot cover all of the C. Is it true?

Running Noob
  • 21
  • 1
  • 1
  • You should point your attention on pointers, especially in C. Your problem is solved dynamically allocating memory based on your array's size – somejhereandthere Oct 10 '19 at 09:16

2 Answers2

5

Use std::vector in C++. The storage of the vector is handled automatically, being expanded and contracted as needed. You should avoid the usage of array if not explicitly required, which I don't think is true for your case.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
ichherzcplusplus
  • 321
  • 1
  • 13
0

Variable length arrays are only available in C, not in C++.

You should use dynamic arrays or std::vector.

size = 17;
int* cxxarray = new int[size];
int* c__array = malloc(sizeof(int)*size);
std::vector<int> vector(size);
cxxarray[7] = 8;
c__array[7] = 8;
vector[7] = 8;
delete[] cxxarray;
free(c__array);
// no need to free vector 
Wolfgang Brehm
  • 1,491
  • 18
  • 21
  • 1
    `alloca()` is not part of standard C nor is is part of standard C++. It is a vendor specific function. Also, it is usually strongly preferable in C++, since it is safer, to use a standard container (like `std::vector`) to manage dynamlcally allocated arrays, rather than using operators `new` and `delete` directly - the way you have presented it implies operator `new` is the better way, and vector a minor alternative. – Peter Oct 10 '19 at 09:27
  • 1
    The OP is obviously referring to VLAs. – Lundin Oct 10 '19 at 09:36
  • @Ludin I'll edit the answer – Wolfgang Brehm Oct 10 '19 at 09:56
  • 1
    Thanks. But some IDE actually apply this to C++. For example, Clion. ` int n;`` cin >> n``int a[n];` is legal in practice. – Running Noob Oct 10 '19 at 11:16
  • @Running Noob Of course a compiler can do whatever it wants, but then you depend on that compiler. – Wolfgang Brehm Oct 10 '19 at 13:56