Static array in function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandromani
    New Member
    • Dec 2007
    • 16

    Static array in function

    Hi,
    just wondering, why does it work when I create a static array with size unknown at compile time inside a function? I.e. small example:
    Code:
    #include <iostream>
    
    void cpy(int a[], unsigned n){
    	int b[n];
    	std::copy(a, a+n, b);
    	std::cout<<b[0]<<" "<<b[1]<<" "<<b[2]<<" "<<b[3]<<" "<<b[4]<<"\n";
    }
    
    int main(int argc, char **argv){
    	unsigned n;
    	std::cin>>n;
    	int a[5]={1,2,3,4,5};
    	cpy(a, n);
    	return 0;
    }
    The code runs fine, the compiler (gcc 4.5.1 / icpc 11.1) does not complain (though if I change int a[5] to int a[n] in main, the code does not compile as expected).
    Is it possibly legal because n is known when local storage is allocated on the stack when the function is called? (Though if I add std::cin>>n; before int b[n] the code still compiles, which is surprising).

    Thanks
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    in your case
    Code:
    void cpy(int a[], unsigned n){
        int b[n];
        std::copy(a, a+n, b);
        std::cout<<b[0]<<" "<<b[1]<<" "<<b[2]<<" "<<b[3]<<" "<<b[4]<<"\n";
    }
    b[] is an automactic local array with memory being allocated at run time on the stack
    if it was static, e.g.
    Code:
    void cpy(int a[], unsigned n){
        static int b[n];
        std::copy(a, a+n, b);
        std::cout<<b[0]<<" "<<b[1]<<" "<<b[2]<<" "<<b[3]<<" "<<b[4]<<"\n";
    }
    memory for static variables is allocated by the compiler at compile time and hence the compiler has to know the size of the array to allocate.
    with gcc the above code gives
    Code:
    xxx.cpp||In function 'void cpy(int*, unsigned int)':|
    xxx.cpp|4|error: storage size of 'b' isn't constant|
    ||=== Build finished: 1 errors, 0 warnings ===|

    Comment

    • sandromani
      New Member
      • Dec 2007
      • 16

      #3
      Ok, makes sense, thanks for the explanation!

      Comment

      Working...