question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

using namespace std;


int main()
{

int i;
cout<<"How many places:";
cin>>i;
int p[i];



if(p==NULL)
{
    cout<<"No memory";
}
else
{

    for(int n=0;n<i;n++)
    {
        cout<<"\nenter:";
        cin>>p[n];
    }

    cout<<"\nYou entered "<<i<<" places to have the array\n";
    for(int n=0;n<i;n++)
    {
        cout<<"\nyou entered:";
        cout<<p[n];
    }


}

cout<<endl;

}

Why this program works?
It compile perfect but should not.
The reason because i am not using memory managment so why it works instead of crashing?
You must be using a compiler with non-standard language extension that allows variable-length arrays (it's a C feature that's not part of C++). See for yourself: http://liveworkspace.org/code/37df4af80c4a435b339a9fd45082dc18

replace int p[i]; with std::vector<int> p(i); for this to work everywhere.
Last edited on
The program should not work. But the reason is another than you think. C++ does not allow to declare arrays with non-const expressions as the array size. So here

int p[i];

the compiler shall issue an error.

But it seems it is an extension of C++ provided by the compiler. So the code is compiled successfully.

As for the "memory management" then it is the compiler that resposible for the memory management because the array is defined in the stack. Your participation is not required.
Last edited on
Also I would like to append that this code (the if statement)

1
2
3
4
5
6
7
if(p==NULL)
{
    cout<<"No memory";
}
else
{
// ... 



has no any sense. If the code was successfully compiled then the address of the first element of an array defined by the compiler in the stack is always unequal to zero. Otherwise the code would not be compiled.
Topic archived. No new replies allowed.