Possible Duplicate:
Static array initialization of individual elements in C++
In C, I can initialize specific subscript item in array like this:
int array[100] = {[22] = {1}, [33] = {33}};
but this snippet can not compile by g++. so how can I initialize specific subscript item in array by c++.
You cannot. This is not legal C++ code.
You'll need to initialize the whole array, and then assign the specific elements later. Perhaps:
int array[100] = {};
array[22] = 1;
array[33] = 33;
The subscript initialization is only allowed in C and not in C++. You can check the detailed documentation here http://publib.boulder.ibm.com/infocenter/compbgpl/v9v111/index.jsp?topic=/com.ibm.xlcpp9.bg.doc/language_ref/aryin.htm
If you want to initialize each element, you can do it after declaring the array and in the following lines initializing the values;
#include<iostream>
using namespace std;
int main(){
int arr[100];
arr[22]=33;
arr[33]=66;
cout<<arr[22]<<"\t"<<arr[33];
return 0;
}
It produces the following output:
$ ./a.exe
33 66
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With