Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize specific subscript item in array by c++ [duplicate]

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++.

like image 843
Xinyu NG Avatar asked Jul 19 '26 14:07

Xinyu NG


2 Answers

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;
like image 124
John Dibling Avatar answered Jul 21 '26 02:07

John Dibling


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
like image 25
Shubhanshu Mishra Avatar answered Jul 21 '26 03:07

Shubhanshu Mishra