Array dimension in c++ 11 [duplicate] - c++

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 16 days ago.
void method(string a) {
int n = a.size();
int array[n];
}
The above code can compile correctly using gcc. How can the size of the array come from a non-constant variable? Does the compiler automatically translate the int array[n] to int* array = new int[n]?

How can the size of the array come from a non-constant variable?
Currently, because that compiler has a non-standard extension which allows you to use C's variable length arrays in C++ programs.
Does the compiler automatically translate the int array[n] to int* array = new int[n]?
That's an implementation detail. I believe GCC places it on the stack, like normal automatic variables. It may or may not use dynamic allocation if the size is too large for the stack; I don't know myself.

dynamic allocation. The new keyword will do this with a pointer and some allocation.
int * ptr;
int n = a.size();
ptr = new int[n];

According to this the compiler allows this expression in C++ as far as C90/99.

Related

Visual Studio Community 2019 requires a constant value inside square brackets [duplicate]

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 2 years ago.
I've been trying to find answers for this lately, but I just can't seem to understand why the compilers for C++ that Microsoft has been using can't compile such a code :
#include<iostream>
int main()
{
int n;
std::cin >> n;
int x[n];
}
It gives those errors :
However, this code compiles on a lot of different compilers.
Could someone point me to somewhere, I couldn't find any answers for this.
See How to make an array with a dynamic size? General usage of dynamic arrays (maybe pointers too)? for discussion on the matter. Briefly, C++ requires that raw arrays have a constexpr for their size, so they it knows how much memory to allocate for it at the moment it's declared instead of at runtime after receiving user input. Some compilers I suppose are more permissive on this.
Variable length arrays are not standard C++. Some compilers provide them as a language extension but they are not portable.
This code shouldn't compile.
In C++, arrays are statically allocated and their required memory must be specified at compile time.
Hence, a user input is not a suitable value for array declaration. If you want a dynamic array, you can try using malloc like this:
#include<iostream>
int main()
{
int n;
std::cin >> n;
int* x = (int*)malloc(n*sizeof(int));
}
This way, the array is actually stored in heap, and can have any arbitrary size, changing over lifetime of the program.
Another alternative is std::vector of course.

Using variable to initialize an array in C++ [duplicate]

This question already has answers here:
In C++ books, array bound must be constant expression, but why the following code works?
(2 answers)
Closed 5 years ago.
As C++ primer said, we can't use variable as the dimension of builtin array, so the following code did not work
int length = 3;
int array[length] = {0, 1, 2};
the error is
error: variable-sized object may not be initialized
But why following code works?
int length = 3;
int array[length];
This is an extension by your compiler called a Variable Length Array (VLA) and is not in the C++ standard which means that this code can break at any moment you switch compilers or the compiler vendor decides to no longer support this feature. If you want a variable length array that does not depend on this extension but instead on the standard you should use a std::vector.

Why is it possible to add define elements in an array of length 0 in C++ [duplicate]

This question already has answers here:
Array with size 0 [duplicate]
(4 answers)
What is the purpose of allocating a specific amount of memory for arrays in C++?
(5 answers)
Closed 5 years ago.
Im reading up for a exam in C++ and just fideling around in order to get a better sense of the language. My understanding is that arrays in c++ are defined with a fixed length either before run time or dynamically. Knowing this I don't understand why C++ accepts this. I wouldn't think that it would be possible to add element to an array of length 0;
int * TestArray = new int[0];
TestArray[0]=10;
TestArray[1]=20;
TestArray[2]=30;
Writing to array elements outside of the valid size is Undefined Behaviour. It's a bug and your program is ill formed. But the compiler is not required to issue a diagnostic (although most will with the right warning options).
It's your responsibility to follow the rules.
You may not access any elements in a zero sized array. It results in undefined runtime behavior.
However, zero sized arrays are allowed for various reasons.
First, it allows you to make functions less complicated by skipping size checks:
void f(size_t n)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
instead of:
void f(size_t n)
{
if (n>0)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
}
Second, the intent was to make it easy for compiler writers to implement new using malloc, and this is the defined behavior for malloc.
The GCC c compiler docs give this reason:
"Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object: "
struct line {
int length;
char contents[0];
};
struct line *thisline = (struct line *)
malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
[without it], you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.
My professor told me that because c++ and c can access and write outside of array bounds,it is one of the main reasons they are used to create operating systems. For example you can even do something like
arr[-1]=5;
I believe it is worth mentioning.However this can lead to undefined behavior.

Array Size Declaration issue [duplicate]

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 8 years ago.
int n=5;
int arr[n];
I want to declare size of array as above in C++, but I get error while compiling. I find a lot of code in internet which uses these type of declaration instead of simple putting int arr[5]. How come the code compiles successfully for them but not for me. P.S: I use windows7 and Visual Studio(IDE).
Error Message : Expresion must have a constant value
The number of elements of the array, the array bound, must be a constant expression.
You have to use
const int n = 5;
or
constexpr int n = 5;
else it is a non standard extension : variable length array (VLA).
The error message actually describes rather well what’s going on: C++ does not support arrays with a non-constant size (more precisely, the size needs to be known at compile time).
There are two solutions for this:
If the size is actually a constant, declare it as constexpr (if you can’t use C++11, you can also use const):
constexpr int n = 5;
std::array<int, n> arr;
Which requires the standard header <array>. Or, if you cannot use C++11, change the second line to
int arr[n];
If the size isn’t known at compile time, don’t use a static array, use a dynamic container instead:
int n = 5;
std::vector<int> arr(n);
This requires the <vector> standard header.

int a[0]; What is the use of this statement? Where does it makes sense? [duplicate]

This question already has answers here:
Flexible Array Member (Zero Length Array) [duplicate]
(2 answers)
How to include a dynamic array INSIDE a struct in C?
(8 answers)
Closed 8 years ago.
I have seen the usage of this statement in driver programs at the end of the structure.
Can anyone explain me what is the use of this statement? and how does it works internally?
I mean will compiler considers it as array or a variable?
In C, it's a trick to allow you to put a variable-sized array at the end of a structure, by allocating enough memory for both the fixed-sized fields and whatever you want in the array. For example:
struct array {
size_t size;
int a[]; // strictly, it should be incomplete rather than zero sized
};
struct array * make_array(size_t size) {
struct array * array = malloc(sizeof (struct array) + size * sizeof (int));
array->size = size;
return array;
}
struct array * array = make_array(2);
array->a[1] = 42; // No problem: there's enough memory for two array elements
In C++, it's not valid. Use std::vector instead.
While arrays of size 0 are not supported by either standard, many compilers allow them as an extension. The standardised C way (C99+) instead leaves out the size altogether.
Thiis is used to describe a data-structure consisting of the starting fields and a variable number of array elements, as well as for comfortable access to them.