配列は一連のデータを連続に格納しているから、ポインタ演算は配列を示すときに意味を持つ。
#include<iostream> using namespace std; void main(){ int a[] = {4,6,8,10,12}; cout << "配列要素(1):配列を直接参照" << endl; int i; for(i=0; i<5; i++) cout << "a[" << i << "] = " << a[i] << endl; int *ptr = &a[0]; cout << endl << "配列要素(2):間接参照" << endl; for(i=0; i<5; i++) cout << "*(ptr+)" << i << ") = " << *(ptr+i) << enld; cout << endl << "配列要素(3):間接参照" << endl; for(i=0; i<5; i++) cout << "*ptr++ = " << *ptr++ << endl; return 0; }
配列要素(1):配列を直接参照 a[0] = 4 a[1] = 6 a[2] = 8 a[3] = 10 a[4] = 12 配列要素(2):間接参照 *(ptr+0) = 4 *(ptr+1) = 6 *(ptr+2) = 8 *(ptr+3) = 10 *(ptr+4) = 12 配列要素(3):間接参照 *ptr++ = 4 *ptr++ = 6 *ptr++ = 8 *prt++ = 10 *ptr++ = 12
コメントをかく