### 配列の要素を出力
int main() {
int test[5];
test[0] = 80;
test[1] = 60;
test[2] = 22;
test[3] = 50;
test[4] = 75;
for(int i=0; i<5; i++) {
cout << i+1 << "番目の人の点数は" << test[i] << "です。\n";
}
return 0;
}
### キーボードから入力
int main() {
const int num = 5;
int test[num];
cout << num << "人の点数を入力してください。\n";
for(int i=0; i<num; i++) {
cin >> test[i];
}
for(int j=0; j<num; j++) {
cout << j+1 << "番目の人の点数は" << test[j] << "です。\n";
}
return 0;
}
### 配列の要素をソートする
int main() {
const int num = 5;
int test[num];
cout << num << "人の点数を入力してください。\n";
for(int i=0; i<num; i++) {
cin >> test[i];
}
for(int s=0; s<num-1; s++) {
for(int t=s+1; t<num; t++) {
if(test[t] > test[s]){
int tmp = test[t];
test[t] = test[s];
test[s] = tmp;
}
}
}
for(int j=0; j<num; j++) {
cout << j+1 << "番目の人の点数は" << test[j] << "です。\n";
}
return 0;
}
### 多次元配列
int main() {
const int sub = 2;
const int num = 5;
int test[sub][num];
test[0][0] = 80;
test[0][1] = 60;
test[0][2] = 22;
test[0][3] = 50;
test[0][4] = 75;
test[1][0] = 90;
test[1][1] = 55;
test[1][2] = 68;
test[1][3] = 72;
test[1][4] = 58;
for(int i=0; i<num; i++) {
cout << i+1 << "番目の人の国語の点数は" << test[0][i] << "です。\n";
cout << i+1 << "番目の人の算数の点数は" << test[1][i] << "です。\n";
}
### 配列とポインタ
配列のアドレス
&test[0]
&test[1]
配列名を記載しただけで、先頭要素のアドレスを表す
test
int main() {
int test[5] = {80, 60, 55, 22, 75};
cout << "test[0]の値は" << test[0] << "です。\n";
cout << "test[0]のアドレスは" << &test[0] << "です。\n";
cout << "testの値は" << test << "です。\n";
cout << "つまり*testの値は" << *test << "です。\n";
return 0;
}
$ g++ -o sample sample.cpp && ./sample
test[0]の値は80です。
test[0]のアドレスは0xfffff9b40360です。
testの値は0xfffff9b40360です。
つまり*testの値は80です。
*testは配列の先頭要素の値となる。
### ポインタの演算
int main() {
int test[5] = {80, 60, 55, 22, 75};
cout << "test[0]の値は" << test[0] << "です。\n";
cout << "test[0]のアドレスは" << &test[0] << "です。\n";
cout << "testの値は" << test << "です。\n";
cout << "test+1の値は" << test+1 << "です。\n";
cout << "*(test+1)の値は" << *(test+1) << "です。\n";
return 0;
}
$ g++ -o sample sample.cpp && ./sample
test[0]の値は80です。
test[0]のアドレスは0xffffe4e0e070です。
testの値は0xffffe4e0e070です。
test+1の値は0xffffe4e0e074です。
*(test+1)の値は60です。