These are two simple programs. In first program, i used static array, while in second program i used dynamic array. Both programs do the same job i.e. initiaze the array by asking the user to enter the their test scores.

The problem is:
1)i have read in many books that we can't use static array if we do not know the exact size of the array. instead of this we just use dynamic array. but in both these programs we do not know the size of the array.
** according to above statement my first program should not run but it runs correcly.

so i want to know what is the difference these two programs as they do the same job.

// static array

#include<iostream>
using namespace std;

int main()
{
  int size;

  cout<<"enter number of students"<<endl;
  cin>> size;

  int array [size];

  for(int i =0; i< size; i++)
  {
   cout<< "enter marks of "<< (i+1) << " student: ";
   cin >> array [i];
  }    

return 0;      
}





#include<iostream>
using namespace std;

int main()
{
 int size;
 int * ptr;

 cout<<"enter number of students"<<endl;
 cin>> size;

 ptr =new int [size];      

 for(int i = 0; i< size; i++)
  {
   cout<< "enter marks of "<< (i+1) << " student: ";
   cin >> ptr [i];
  }


 delete [] ptr;
 ptr = 0;

 return 0;         

}

Recommended Answers

All 9 Replies

Static arrays are allocated on the stack and they have fixed sized, e.g. their size cannot be changed, either shortened or expanded.
Dynamic arrays are allocated on the heap. You set their size and than even change it, making them "dynamic". In order to use these kinds of arrays you'll need to allocate space for them and to deallocate them manually (when not needed). e.g.

int a = new int[2];

//and

delete [] a;

Static arrays on the other hand are deallocated automatically when they aren't needed anymore.

Thanks Lucaci Andrew, but that is not the answer of my question
as u said that static arrays have fixed sized and thus size can not be changed. but see me first program, i do not used a const size, see lines 8 to 13

  int size; // not constant

  cout<<"enter number of students"<<endl;
  cin>> size;

  int array [size];

so, in this case when i did not used constant size thus can be used in that cases where we do not know the exact memory for the array(as we are asking the user to enter the number of students). in otherwords it fulfill the requirement of dynamic memory allocation although we dont used new operator.

The code in your first piece of code should not compile. More than likely there is some sort of compiler extension taking care of it for you. What compiler are you using? Static arrays can only be initialized with a const size argument.

From what I've seen, MinGW compilers take care of your above mentioned situation (as Nathan stated), but on VS I get this:

1>e:...\~staticarrays.cpp(13): error C2057: expected constant expression
1>e:...\~staticarrays.cpp(13): error C2466: cannot allocate an array of constant size 0
1>e:...\~staticarrays.cpp(13): error C2133: 'a' : unknown size

on a simple defined program:

#include "stdafx.h"
#include <iostream>
using namespace std;

int main(){
    int size;
    cout<<"Size: ";
    cin>>size;
    int a[size];
    return 0;
}

So I guess that exaplins your misunderstanding.

I did get this off C++ online documentation:
NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.
Click Here

The reason why your code compiles is because your compiler implements a non-standard extension called VLA (Variable Length Arrays). This is a C99 feature (1999 C language standard) which allows for "static" arrays to have a length that is determined at run-time (not a compile-time constant). It is not standard in C++ but some compilers allow it in C++ too as an extension, most notably GCC. Some compiler versions even enable it by default, which I guess is the case for your compiler.

Thanks NathanOliver, Lucaci Andrew, mike_2000_17, vijayan121

I am currently using Dev c++ compiler. But on the basis of above replies, i also compiled the first program in Code Blocks and both compliers compiled the program successfully with no erros.

so is that mean both (Dev c++ & Code blocks) are GCC and have a non standard VLA exetention? If it is then the question arise how to disable this non standard exention Vla to get to correct results?

how to disable this non standard exention Vla to get to correct results?

Compile with g++ -std=c++11 -pedantic-errors

With GCC 4.9:

    #include <stdexcept>
    #include <iostream>

    int foo( int arg )
    {
        int a[arg] = { 1, 2, 3, 4 } ;
        int s = 0 ;
        for( int v : a ) s += v ;
        return s ;
    }

    void bar( int arg )
    {
        try
        {
            std::cout << "try foo( " << arg << " ): " ;
            foo(arg) ;
            std::cout << "ok\n" << std::flush ;
        }
        catch( const std::exception& e ) { std::cerr << "exception - what: " << e.what() << '\n' ; }
    }

    int main()
    {
        bar(1) ;
        bar(4) ;
        bar(10) ;
        bar(-1) ;
    }

.

g++ -std=c++11 -pedantic-errors -Wall -Wextra test.cc && ./a.out
temp.cc: In function 'int foo(int)':
temp.cc:6:14: error: ISO C++ forbids variable length array 'a' [-Wvla]
      int a[arg] = { 1, 2, 3, 4 } ;
               ^  

.

g++ -std=c++1y -pedantic-errors -Wall -Wextra test.cc && ./a.out
try foo( 1 ): exception - what: std::bad_array_length
try foo( 4 ): ok
try foo( 10 ): ok
try foo( -1 ): exception - what: std::bad_array_length
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.