简体   繁体   中英

Initialization of 1D array

I have this simple code and I need to initialize the Range[] array, but I get this error:

 >gcc c.cpp c.cpp: In function 'int main()': c.cpp:16:7: error: expected primary-expression before ']' token Range[]={12,22,35,45,69,74,79,78,66};

How can solve it please?

#include <iostream>
#include <string.h>
#include <sstream>
    
using namespace std;
using std::string;
    
int Range[8]; 
    
int main(){
       
    Range[]={12,22,35,45,69,74,79,78,66};
    
    for(int i=0;i<8;i++){
       cout<< Range[i] <<endl;
    }
    return 0;
}

What you're doing is actually assignment and not initialization.

And you can't assign to an array, just copy to it.

The solution? Do actual initialization:

int Range[]={12,22,35,45,69,74,79,78,66};

Note that since I didn't specify a size for the array, the compiler will automatically set the size to nine elements, as in the initializer list. Unlike your current definition of the array where you set the size to only eight elements.

I also recommend you make the variable a local variable inside the main function. Global variables are to be avoided.

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