所以我知道 * 運算子用于乘法和作為指標,但有時我看到 * 運算子但我不確定它的含義。看看這個定義矩陣的代碼
#ifndef MATRIX_H
#define MATRIX_H
/* The data structure representing a matrix */
typedef struct {
int rows; /* number of rows */
int columns; /* nuumber of columns */
int **content; /* matrix elements in a two dimensional array */
} matrix_t;
雙星號在這里是做什么用的?
我假設 ** 運算子用于二維陣列中的指標,但我不確定。
uj5u.com熱心網友回復:
多重間接是一件事-您可以擁有指向指標的指標,指向指標的指標,指向指標陣列的指標,指向指標的指標陣列,指向指標陣列的指標,指向指向回傳指標的函式的指標陣列等。
如此處使用的,目的是分配一個指標陣列:
matrix_t mat;
mat.content = calloc( 2, sizeof *mat.content );
這給了我們
int ** int *
--- ---
mat.content: | | ---> | | mat.content[0]
--- ---
| | mat.content[1]
---
然后為每個指標分配一個陣列int:
for ( size_t i = 0; i < rows; i )
mat.content[i] = calloc( 2, sizeof *mat.content[i] );
給我們
int ** int * int
--- --- ---
mat.content: | | ---> | | mat.content[0] ---> | | mat.content[0][0]
--- --- ---
| | mat.content[1] - | | mat.content[0][1]
--- | ---
|
|
| ---
-> | | mat.content[1][0]
---
| | mat.content[1][1]
---
運算式 mat.content有型別,int **所以運算式*mat.content有型別int *;因此,sizeof *mat.content == sizeof (int *). 同樣,運算式mat.content[i]也有型別int *( *p == p[0]),所以*mat.content[i]有型別int,所以sizeof *mat.content[i] == sizeof (int)。
由于陣列下標的作業方式,mat.content[i][j]其作業方式與您宣告mat.content為int. 它不是將所有行都分配在一個連續的塊中,而是零碎地分配。
通用規則:
T *p; // p is a pointer to T
T *ap[N]; // ap is an array of pointer to T
T (*pa)[N]; // pa is a pointer to an array of T
T *fp(); // fp is a function that returns pointer to T
T (*pf)(); // pf is a pointer to a function that returns T
T **p; // p is a pointer to a pointer to T
T ***p; // p is a pointer to a pointer to a pointer to T
const T *p; // p is a pointer to const T - you can write to p, but not *p
T const *p; // same as above
T * const p; // p is a const pointer to T - you can write to *p, but not to p
在運算式中使用時,*“取消參考”指標 - 如果您有類似的宣告
int x;
int *p = &x;
該運算式 *p充當 的別名x:
*p = 10; // does the same thing as x = 10;
該物件p存盤 的位置x,運算式的型別p是int *(指向 int 的指標)。運算式*p等價于運算式x- 它不僅產生存盤在 中的值x,還可以向x through *p寫入新值,如上所示。
上面的宣告給了我們這種關系:
p == &x // int * == int *
*p == x // int == int
陣列下標運算式a[i]定義為- 給定由 指定的起始地址,從該地址偏移元素(不是位元組!)并取消參考結果。*(a i)ai
*p == *(p 0) == p[0]
陣列不是指標,它們也不存盤指向其第一個元素的指標。除非它是、 或一元運算子的運算元sizeof,或者是用于在宣告中初始化字符陣列的字串文字,否則“N 元素陣列”型別的運算式將被轉換或“衰減”為型別為“pointer to ”的運算式,運算式的值將是第一個元素的地址。這很重要——如果你宣告一個陣列_Alignof&TT
int a[10];
a不將地址存盤到其第一個元素;相反,只要編譯器在上面列出的背景關系之外看到運算式 a,它就會基本上將其替換為等效于&a[0].
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532311.html
標籤:C指针
上一篇:將指向void的指標轉換為指向A型別指標的指標并取消參考與將指向void的指標轉換為A型別:為什么?
下一篇:在樹中插入節點并顯示這棵樹
