why to use pointers instead of this?and it has the same result?

why i should use:

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
 #include <iostream>
#include <new>

using namespace std;
int main (void)
{
    int i , n;
    int *p;


cout<<"how many numbers would you like to type?"<<endl;
cin>>i;

p = new int [i];


    for (n=0 ; n<i ; n++)
    {
        cout<<"enter a number :";
        cin>>p[n];
    }

cout<<"you have entered :";

for (n = 0 ; n<i ; n++)
{
    cout<<p[n]<<", "<<endl;

}

delete [] p;

return 0;
}


instead of

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
#include <iostream>
#include <new>

using namespace std;
int main (void)
{
    int i , n;


cout<<"how many numbers would you like to type?"<<endl;
cin>>i;

int p [i];


    for (n=0 ; n<i ; n++)
    {
        cout<<"enter a number :";
        cin>>p[n];
    }

cout<<"you have entered :";

for (n = 0 ; n<i ; n++)
{
    cout<<p[n]<<", "<<endl;

}

return 0;
}


why to use pointers in the first one and it have the same result?
The second example uses a C99 feature that allows you to specify a variable as an array size. It is not available in C++. GNU C++ pulls it in, to make it behave correctly you need to specify -pedantic on the compiler line. https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

This feature uses alloca() to get the memory, which takes it from the stack. The first example uses the heap. http://www.freebsd.org/cgi/man.cgi?query=alloca&apropos=0&sektion=0&manpath=FreeBSD+10.1-RELEASE&arch=default&format=html

This stuff applies: http://www.cplusplus.com/forum/beginner/145631/#msg767515
Last edited on
In the first one, you can later resize the array. You cant in the second one.
Hi,

Does the second one compile? I am guessing not.

Cheers :+)
it does
it does
...or not
error: ISO C++ forbids variable length arrays  

This code will compile only for you and those who happens to have this specific extension enabled. It would not compile for anyone else, or even might behave differently for people with another similar extension.

YOu should not use non-standard compiler extensions and should stick to the standard instead.

To do that, enable pedantic warnings (or threat hem as errors) and specify used standard explicitely.
Topic archived. No new replies allowed.