[英]access to an array of pointers in c
將其定義為一維時,為什么要訪問帶有兩個參數的指針數組?
我知道,我必須使用一個指針數組來訪問函數中的多維數組,但是我不知道為什么我可以使用兩個參數來訪問指針數組。
int a[m][l] { 1,2,3,4, 2,3,4,5, 3,4,5,6 }; //some matrices
int c[m][l];
int *ap[m]; //array of pointers one-dimensional
int i,j;
for (i = 0; i < m; i++) //passing the address of first element in each
ap[i] = a[i]; //colon of matrix to array of pointers
for (j = 0; j < m; j++)
bp[i] = b[i];
dosomethingwithmatrix(ap[0], bp[0], m, l);
int* dosomethingwithmatrix(const int*ap[], int* bp[])
{
cp[i][j] = ap[i][j] //accss the array of pointers with two parameters
}
同樣在C語言中,數組會衰減為指針。
從標准(C99 6.3.2.1/3-其他操作數-左值,數組和函數指示符):
除非它是sizeof運算符或一元&運算符的操作數,或者是用於初始化數組的字符串文字,否則將類型為“ array of type”的表達式轉換為類型為“ pointer to to”的表達式類型'',它指向數組對象的初始元素,不是左值。
所以:
array[i] "decays" to pointer[i]
where pointer has the address of the [0]th element of array
既然我們已經看到了:
p[i] == *(p + i)
我們要做的就是向指針添加偏移量。
順便說一句,由於加法是可交換的, *(p + i) == *(i + p)
,它有時會給出令人驚訝的結果:
3["hello world"]
是一個完全有效的C表達式(它等於"hello world"[3]
)。
因為您可以用索引符號取消引用指針。 首先,使用索引訪問元素( 指針 ),現在也可以使用索引對指針進行解引用。
與間接運算符之間的等價如下
pointer[i] == *(pointer + i);
在您的情況下,允許ap[i][j]
,因為它有意義。
讓我們檢查數據類型。
對於int *ap[m];
, ap
是int *
s的數組。 對於函數參數int*ap[]
, ap
是指向int指針的指針。
然后, ap[k]
(指的是上一點)是一個int *
。 這很可能是已分配的內存,可以提供對多個int
的有效訪問。
如果分配了足夠的內存, ap[k][s]
將引用一個int
。
函數dosomethingwithmatrix
的參數ap
和bp
都是指向int的指針 。 它們不是指針數組。 功能說明符
int* dosomethingwithmatrix(const int *ap[], int *bp[])
相當於
int* dosomethingwithmatrix(const int **ap, int **bp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.