C++ array, setting arraysize during run time [duplicate] - c++

This question already has answers here:
Array size at run time without dynamic allocation is allowed? [duplicate]
(8 answers)
Closed 6 years ago.
I am reading C++ Primer plus on arrays, and it says the following
typeName arrayName[arraySize];
//Arraysize cannot be a variable whose value is set while the program is running"
However, I wrote a program
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int array[n];
for(int i=0; i<n; i++)
{
cout<<array[i]<<endl;
}
}
And it works fine, I am able to set the size of the array during run time. I am not getting any compilation errors, or run time crashes.
Can someone explain what is happening?
Thanks

Some compilers like g++ allow the use of C variable length arrays and will happily compile the code without any warnings or error. This is not standard and is a compiler extension.
If you need an "array" and you do not know what the size will be until run time then I suggest you use a std::vector You can use it as a direct replacement to an array but it allows run time sizing and it offers a lot of other useful features.

Related

Pointer takes elements bigger than its size in c++ [duplicate]

This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 10 months ago.
When creating a pointer using new keyword or <stdlib.h>'s malloc, and put its size 0; what ever is the index number it doesnt give an error and works. ( i am not sure if this works if the size bigger then 0, because some times when i allocate a memory block and place an element outside its range program crashes).
My question : is this a c++ thing? Or just from my compiler? Is it safe to use it for arrays i don't want to limit it with specific size. Because i am thinking to use this in my game to make unlimited world generation and save it ( Not all terrain just the breakable and placable objects)
#include <iostream>
using namespace std;
int main() {
int* x = new int[0];
x[100] = 0;
cout << x[100];
return 0;
}
is this a c++ thing? Or just from my compiler?
It's a bug in your program. The behaviour of the program is undefined.
Is it safe to use it
It is not safe. The program is broken.

How is static array expanding itself? [duplicate]

This question already has answers here:
Why is it that we can write outside of bounds in C?
(7 answers)
Is accessing a global array outside its bound undefined behavior?
(8 answers)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 11 months ago.
I wrote a code for entering element and displaying the array at the same time. The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements? Code:
#include <iostream>
using namespace std;
void display(char arr[],int n)
{
for(int i=0; i<n; i++)
cout<<arr[i]<<" ";
return;
}
int main()
{
char A[4];
int i=0;
char c;
for(;;)
{
cout<<"Enter an element (enter p to end): ";
cin>>c;
if(c=='p')
break;
A[i]=c;
i++;
display(A,i);
system("clear");
}
return 0;
}
Writing outside of an array by using an index that is negative or too big is "undefined behavior" and that doesn't mean that the program will halt with an error.
Undefined behavior means that anything can happen and the most dangerous form this can take (and it happens often) is that nothing happens; i.e. the program seems to be "working" anyway.
However maybe that later, possibly one million instructions executed later, a perfectly good and valid section of code will behave in absurd ways.
The C++ language has been designed around the idea that performance is extremely important and that programmers make no mistakes; therefore the runtime doesn't waste time checking if array indexes are correct (what's the point if the programmers never use invalid ones? it's just a waste of time).
If you write outside of an array what normally happens is that you're overwriting other things in bad ways, possibly breaking complex data structures containing pointers or other indexes that later will trigger strange behaviors. This in turn will get more code to do even crazier things and finally, some code will do something that is so bad that even the OS (that doesn't know what the program wants to do) can tell the operation is nonsense (for example because you're trying to write outside the whole address space that was given to the process) and kills your program (segfault).
Inspecting where the segfault is coming from unfortunately will only reveal what was the last victim in which the code is correct but that was using a data structure that was corrupted by others, not the first offender.
Just don't make mistakes, ok? :-)
The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements?
The code has a bug. It will not work correctly until you fix the bug. It really is that simple.

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.

Why this C++ program complies and runs in CodeBlocks [duplicate]

This question already has answers here:
Declaring an array of negative length
(3 answers)
Closed 8 years ago.
#include <iostream>
using namespace std;
int main()
{
cout<<"started "<<endl;
int n= -2;
int array[n];
array[0]=100;
array[1]=200;
cout<<array[0]<<endl;
cout<<array[1]<<endl;
cout<<"over"<<endl;
return 0;
}
Why does this compile and run? I expected a compilation error because value of n is negative.
Variable-length arrays are not a C++ feature, so this line will cause a compilation error in a compiler that is ordered to strictly adhere to the C++ specification, regardless of the value of n (unless n is const and can be determined at compile-time):
int array[n];
Likely you are using a compiler that supports variable-length arrays as an extension. Therefore, the rules regarding what is valid depend entirely on the specific compiler and compiler options, and any code that you write using this extension will not be portable to compilers that don't support this non-standard feature.

Array of non-constant size: Why does this even work? [duplicate]

This question already has answers here:
C++: Why does int array[size] work?
(3 answers)
Closed 8 years ago.
#include <iostream>
using namespace std;
int main(){
int n;
cout<<"Enter the size :";
cin>>n;
int array[n]; // I've worked some outputs and it works
return 0;
}
Is this some kind of dynamic allocation?
Why doesn't it even gives an error for 'n' to be a "const"?
Also, writing cout << array[n+5]; doesn't result in an compile time or runtime error.
I'm using Dev-C++.
Apparently one can declare variable length arrays in C99, and it seems GCC accepts then for C++ also.
Variable-length automatic arrays are allowed in ISO C99, and as an
extension GCC accepts them in C90 mode and in C++. These arrays are
declared like any other automatic arrays, but with a length that is
not a constant expression.
You learn something every day .. I hadn't seen that before.