3 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊
char A[WIDTH][HEIGHT]; A=rand_grid(WIDTH,HEIGHT);
char (*foo(int width))[HEIGHT]{ /** * dynamically allocate memory for a widthxHEIGHT array of char */ char (*newArr)[HEIGHT] = malloc(sizeof *newArr * width); /** * initialize array contents here */ return newArr;}
foo -- foo foo(int width) -- is a function -- taking an int parameter *foo(int width) -- returning a pointer (*foo(int width))[HEIGHT] -- to a HEIGHT-element arraychar (*foo(int width))[HEIGHT] -- of char
void foo (T *p) {...}...T arr[N];foo(arr);
void foo (T (*p)[M]) {...}...T arr[N][M];foo(arr);
void foo(T *base, size_t rows, size_t cols) {...}...T arr[N][M];foo (&arr[0][0], N, M);
void rand_grid(char *base, size_t rows, size_t cols){ size_t i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { /** * Since base is a simple char *, we must index it * as though it points to a 1-d array. This works if * base points to the first element of a 2-d array, * since multi-dimensional arrays are contiguous. */ base[i*cols+j] = initial_value(); } }}int main(void){ char A[WIDTH][HEIGHT]; rand_grid(&A[0][0], WIDTH, HEIGHT); ...}
即使這些表情 &A[0][0]
和 A
產(chǎn)生相同的值(A的基址),這兩個(gè)表達(dá)式的類型是不同的。第一個(gè)表達(dá)式計(jì)算為指向char的簡(jiǎn)單指針( char *
),而第二個(gè)值計(jì)算為指向char的二維數(shù)組的指針( char (*)[HEIGHT]
).

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
auto
struct
malloc()
struct
.
struct
#define WIDTH 11#define HEIGHT 11typedef struct { unsigned char cell[WIDTH * HEIGHT];} Board;Board board_new(void){ Board b; size_t i; for(i = 0; i < sizeof b.cell / sizeof *b.cell; i++) b.cell[i] = rand() & 255; return b;}
void board_init(Board *b);
- 3 回答
- 0 關(guān)注
- 530 瀏覽
添加回答
舉報(bào)