3 回答
TA贡献1846条经验 获得超7个赞
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
产生相同的值(A的基址),这两个表达式的类型是不同的。第一个表达式计算为指向char的简单指针( char *
),而第二个值计算为指向char的二维数组的指针( char (*)[HEIGHT]
).
TA贡献1799条经验 获得超8个赞
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 关注
- 356 浏览
添加回答
举报