這篇文章主要介紹了C語言中指針數組與數組指針的區別,是C語言入門學習中的基礎知識,需要的朋友可以參考下
首先來分別看一下,指針數組的一個小例子:
- #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;
- }
數組指針:
- #include <stdio.h>
- int main()
- {
- int i;
- int* pI = &i; //普通類型
- typedef int(AINT5)[5];
- AINT5* p1;
- int array[5];
- p1 = &array; //數組指針1
- int (*p2)[5] = &array; //數組指針2(不建議這樣寫)
- int (*p3)[4] = &array; // X 數組指針3(不建議這樣寫)
- return 0;
- }
這兩個名字不同當然所代表的意思也就不同。我剛開始看到這就嚇到了,主要是中文太博大精深了,整這樣的簡稱太專業了,把人都繞暈了。從英文解釋或中文全稱看就比較容易理解。
指針數組:array of pointers,即用于存儲指針的數組,也就是數組元素都是指針
數組指針:a pointer to an array,即指向數組的指針
還要注意的是他們用法的區別,下面舉例說明。
int* a[4] 指針數組
表示:數組a中的元素都為int型指針
元素表示:*a[i] *(a[i])是一樣的,因為[]優先級高于*
int (*a)[4] 數組指針
表示:指向數組a的指針
元素表示:(*a)[i]
注意:在實際應用中,對于指針數組,我們經常這樣使用:
- typedef int* pInt;
- pInt a[4];
這跟上面指針數組定義所表達的意思是一樣的,只不過采取了類型變換。
代碼演示如下:
- #include <iostream>
- using namespace std;
- int main()
- {
- int c[4]={1,2,3,4};
- int *a[4]; //指針數組
- int (*b)[4]; //數組指針
- b=&c;
- //將數組c中元素賦給數組a
- for(int i=0;i<4;i++)
- {
- a[i]=&c[i];
- }
- //輸出看下結果
- cout<<*a[1]<<endl; //輸出2就對
- cout<<(*b)[2]<<endl; //輸出3就對
- return 0;
- }
注意:定義了數組指針,該指針指向這個數組的首地址,必須給指針指定一個地址,容易犯的錯得就是,不給b地址,直接用(*b)[i]=c[i]給數組b中元素賦值,這時數組指針不知道指向哪里,調試時可能沒錯,但運行時肯定出現問題,使用指針時要注意這個問題。但為什么a就不用給他地址呢,a的元素是指針,實際上for循環內已經給數組a中元素指定地址了。但若在for循環內寫*a[i]=c[i],這同樣會出問題??傊痪湓?,定義了指針一定要知道指針指向哪里,不然要悲劇。
新聞熱點
疑難解答