简体   繁体   中英

Why can't I access my array subscript in global scope

If I have the following code in a function, I will not get an error and I can compile no problem, however, once I put it in global scope I will get an error for "cannot allocate an array of size zero", along with several other errors. Why does this happen and how can I get rid of the errors. I am aware of the risk of global variables, this is just a simple test case.

int* intest[2];
intest[0] = new int;

You are allowed declarations in global scope but not allowed to use the new operator or the assignment. Thus you need the declaration int *intest[2] in global scope (and all your code would see it) but C++ requires the new to be in the sequence of your main code. (probably in some sort of start up function for the app).

EDIT: as pointed out by @phresnel you can use the new operator in this scope but not the assignment (this is unusual but not illegal). However the following new operators used as initiation will work for you:

int *x[2]={new int,new int};

In general the use of such a global buffer is highly discouraged and is considered an anti-pattern - if you can avoid using it you probably should.

int* intest[2];

Is valid placing in the local scope however :

intest[0] = new int;

is not.

The difference is that the upper one is a initalisation statement (creating the variable) and the lower one is a executed code segment.

Code that should be "executed" cant be called in the global scope, for example you cant call a function in the global scope. When would that function be called?

I can create how many variables i want in the global scope but i cant run code from it except from constructors being called when initialisating the global variables.

If you want to execute code such as :

intest[0] = new int;

You would have to execute it trough main or another function, otherwise the program would not know when to execute it.

AFAIK, the global scope only allow u put define and declaration on it. Whereas intest[0] = new int; is a assignment that c/c++ compiler shall fail while compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM