Part6 數組、指針與字符串 6.6指針與數組
阿新 • • 發佈:2017-12-05
遍歷 pre iostream 算術 std 使用數組 變量 col nbsp
數組是一組連續存儲的同類型數據,可以通過指針的算術運算,使指針依次指向數組的各個元素,進而可以遍歷數組。
定義指向數組元素的指針:
int a[10], *pa; pa=&a[0]; 或 pa=a;
經過上述定義及賦值後:
*pa就是a[0],*(pa+1)就是a[1],... ,*(pa+i)就是a[i].
a[i], *(pa+i), *(a+i), pa[i]都是等效的。
//例6-7 (1) 使用數組名和下標訪問數組元素 #include<iostream> using namespace std; int main(){ int a[10] = {1,2,3,4,5,6,7,8,9,0}; for(int i = 0;i < 10; i++) cout << a[i] << " "; cout << endl; return 0; } //例6-7 (2) 使用數組名和指針運算訪問數組元素 #include<iostream> using namespace std; int main(){ int a[10] = {1,2,3,4,5,6,7,8,9,0}; for(int i = 0; i < 10; i++) cout << *(a+i) << ""; cout << endl; return 0; } //例6-7 (3) 使用指針變量訪問數組元素 #include<iostream> using namespace std; int main(){ int a[10] = {1,2,3,4,5,6,7,8,9,0}; for(int *p = a; p<(a+10); p++) cout << *p << " "; cout << endl; return 0; }
指針數組:數組的元素是指針型
//例6-8 利用指針數組存放矩陣#include<iostream> using namespace std; int main(){ int line1[] = {1,0,0};//矩陣的三行 int line2[] = {0,1,0}; int line3[] = {0,0,1}; int *pLine[3] = {line1,line2,line3};//定義整型指針數組並初始化 cout << "Matrix test: " << endl; for(int i = 0;i < 3; i++){ for(int j = 0; j < 3; j++) cout << pLine[i][j] << " "; cout << endl; } return 0; }
Part6 數組、指針與字符串 6.6指針與數組