gpt4 book ai didi

二维数组上下文中的 C 指针

转载 作者:行者123 更新时间:2023-11-30 16:42:00 25 4
gpt4 key购买 nike

这是一个工作程序,它有一个代表迷你棋盘的 8 x 8 数组。实际的棋盘是 4 x 4 的,并且在数组中填充了零。

// Chessboard representation
//
#include <stdio.h>

unsigned char uuboard[8][8]={
{1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1},
{1,1,0,0,0,0,1,1}, {1,1,0,0,0,0,1,1},
{1,1,0,0,0,0,1,1}, {1,1,0,0,0,0,1,1},
{1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1} };

unsigned char *uboard[8]={uuboard[0]+2, uuboard[1]+2, uuboard[2]+2, uuboard[3]+2,
uuboard[4]+2, uuboard[5]+2, uuboard[6]+2, uuboard[7]+2};
unsigned char **board=uboard+2;

int main(void) {
// Make a change to the board directly, using 2-D array
uuboard[3][3] = 8;
printf("Print the board by accessing the 2-D array directly\n");
for (int i=0;i<8;i++) {
for (int j=0;j<8;j++) {
printf("%d", uuboard[i][j]);
}
printf("\n");
}
printf("Print again using pointers\n");
for (int i=0; i<4; i++, printf("\n")) {
for (int j=0; j<4; j++) {
printf("%d", board[i][j]);
}
}
printf("\n");
return 0;
}

最初的程序员似乎使用指针,因此他/她通过从 0 而不是 2 开始索引来到达实际的棋盘方格。这令人费解。 *uboard[8]**board 如何完成这项工作?非常感谢任何答案或对答案的引用。

最佳答案

线路

unsigned char *uboard[8]={uuboard[0]+2, uuboard[1]+2, uuboard[2]+2, uuboard[3]+2, uuboard[4]+2, uuboard[5]+2, uuboard[6]+2, uuboard[7]+2};  

相当于

unsigned char *uboard[8]={&uuboard[0][2], &uuboard[1][2], &uuboard[2][2], &uuboard[3][2], &uuboard[4][2], &uuboard[5][2], &uuboard[6][2], &uuboard[7][2]};  

unsigned char **board=uboard+2;  

相当于

unsigned char **board = &uboard[0]+2; 
// or
unsigned char **board = &uboard[2];

关于二维数组上下文中的 C 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46074743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com