Global arrays in C ++

Why the array does not overflow (for example, an error warning) when the array is declared globally, in another, why can I fill it with an unlimited number of elements (through), even if it is limited by the size in the declaration, and this does when I declare the array locally inside the main ?

char name[9];


int main(){


    int i;


    for( int i=0; i<18; ++i){
    cin>>name[i];


    }

    cout<<"Inside the array: ";
    for(i=0; i<20; i++)
    cout<<name[i];

    return 0;

}
+3
source share
5 answers

C ++ does not have array bounds checked, so the language never checks if you have exceeded the end of your array, but as you might expect, other bad things could happen.

, . , . , . , , . , .

+2

++ . , " undefined", , . , , , .

, std::vector ():

vector <int> a( 3 );   // vector of 3 ints
int n = a.at( 0 );     // ok
n = a.at( 42 );        // throws an exception
+6

undefined. .

+1

. , , . , , .

0

, C/++ . , , , , , , . , , - , .

, , :

int a[10], i;
i = 5;
a[i] = 42;  // Looks normal.
5[a] = 37;  // But what this???
std::cout << "Array element = " << a[i] << std::endl;

- ++. , C/++ .

Neil Butterworth has already commented on the benefits of using std :: vector and the at () access method for him, and I cannot follow up on his recommendation strongly enough. (Unfortunately, the STL designers blew up a great opportunity to make test access to the [] statements, and the at () methods were untested. It probably cost the C ++ developer community millions of hours and millions of dollars and will continue to do so.)

0
source

Source: https://habr.com/ru/post/1759172/


All Articles