首先來分別看一下,指針數(shù)組的一個小例子:
#include <stdio.h> #include <string.h> int lookup_keyword(const char*key, const char* table[], const int size) { int ret = -1; int i = 0; for(i=0; i<size; i++) { if (strcmp(key, table[i]) == 0) { ret = i; break; } } return ret; } #define DIM(array) (sizeof(array)/sizeof(*array)) int main() { const char* keyword[] = { "do", "for", "if", "register", "switch", "while", "case", "static", }; printf("%d/n", lookup_keyword("static", keyword, DIM(keyword))); return 0; }
數(shù)組指針:
#include <stdio.h> int main() { int i; int* pI = &i; //普通類型 typedef int(AINT5)[5]; AINT5* p1; int array[5]; p1 = &array; //數(shù)組指針1 int (*p2)[5] = &array; //數(shù)組指針2(不建議這樣寫) int (*p3)[4] = &array; // X 數(shù)組指針3(不建議這樣寫) return 0; }
這兩個名字不同當然所代表的意思也就不同。我剛開始看到這就嚇到了,主要是中文太博大精深了,整這樣的簡稱太專業(yè)了,把人都繞暈了。從英文解釋或中文全稱看就比較容易理解。
指針數(shù)組:array of pointers,即用于存儲指針的數(shù)組,也就是數(shù)組元素都是指針
數(shù)組指針:a pointer to an array,即指向數(shù)組的指針
還要注意的是他們用法的區(qū)別,下面舉例說明。
int* a[4] 指針數(shù)組
表示:數(shù)組a中的元素都為int型指針
元素表示:*a[i] *(a[i])是一樣的,因為[]優(yōu)先級高于*
int (*a)[4] 數(shù)組指針
表示:指向數(shù)組a的指針
元素表示:(*a)[i]
注意:在實際應用中,對于指針數(shù)組,我們經常這樣使用:
typedef int* pInt;pInt a[4];
這跟上面指針數(shù)組定義所表達的意思是一樣的,只不過采取了類型變換。
代碼演示如下:
#include <iostream> using namespace std; int main(){int c[4]={1,2,3,4};int *a[4]; //指針數(shù)組int (*b)[4]; //數(shù)組指針b=&c;//將數(shù)組c中元素賦給數(shù)組afor(int i=0;i<4;i++){a[i]=&c[i];}//輸出看下結果cout<<*a[1]<<endl; //輸出2就對cout<<(*b)[2]<<endl; //輸出3就對return 0;}
注意:定義了數(shù)組指針,該指針指向這個數(shù)組的首地址,必須給指針指定一個地址,容易犯的錯得就是,不給b地址,直接用(*b)[i]=c[i]給數(shù)組b中元素賦值,這時數(shù)組指針不知道指向哪里,調試時可能沒錯,但運行時肯定出現(xiàn)問題,使用指針時要注意這個問題。但為什么a就不用給他地址呢,a的元素是指針,實際上for循環(huán)內已經給數(shù)組a中元素指定地址了。但若在for循環(huán)內寫*a[i]=c[i],這同樣會出問題。總之一句話,定義了指針一定要知道指針指向哪里,不然要悲劇。
新聞熱點
疑難解答
圖片精選