我memcpy()在 stackoverflow 上找到了適用于字符的作品,但是對于將 2D 陣列的內容復制到另一個陣列沒有很好的答案。
假設我們必須復制以 2D 陣串列示的棋盤游戲的內容,這可以像普通變數一樣通過取消參考來完成嗎?如果不是,該怎么做?這是背景關系的一些代碼:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <assert.h>
int main() {
//copying var using dereferencing
int x = 7;
int copy;
int *copyX = ©
*copyX = x;
printf("%d", copy);
//copying array using dereferencing??
int **board1 = createBoard();
insert(board1, 2, 1);
insert(board1, 5, 2);
int **board2 = createBoard();
*board2 = board1; //can we do this
}
//Requires: nothing.
//Effects: returns a game board initialized with 0s (pointer to 2D array).
int **createBoard() {
//Allocate memory
int **a = (int **)malloc(6 * sizeof(int *));
for (int i = 0; i < 6; i )
a[i] = (int *)malloc(7 * sizeof(int));
//Initialize with zeros
for (int i = 0; i < 6; i ) {
for (int j = 0; j < 7; j ) {
a[i][j] = 0;
}
}
return a;
}
//Requires: pointer to the board to be printed.
//Effects: prints the current state of the game board.
void printBoard(int **board) {
printf("- - - - - - - - - - - - - - - \n");
for (int i = 0; i < 6; i ) {
printf("| ");
for (int j = 0; j < 7; j ) {
printf("%i | ", board[i][j]);
}
printf("\n");
}
printf("- - - - - - - - - - - - - - - \n");
}
//Requires: pointer to the board , column to insert token in, and current player (1 for red, 2 for yellow).
//Effects: inserts token in the game board.
int insert(int **board, int columnNb, int playerTurn) {
if (columnNb < 0 || columnNb >= 7) {
printf("Illegal Move (out of bounds) \n");
return -1;
}
if (board[0][columnNb] != 0) {
printf("Illegal Move (full column) \n");
return -1;
} else {
for (int i = 5; i >= 0; i--) {
if (board[i][columnNb] == 0) { //found the empty cell
board[i][columnNb] = playerTurn; //insert token
}
}
}
return 0;
}
我嘗試取消參考,但事情很復雜,因為malloc()&我對復制是如何發生的感到困惑。
uj5u.com熱心網友回復:
在這個運算式陳述句中
* board2= board1;
左運算元具有型別int *,而右運算元具有型別int **。所以編譯器會發出一條訊息,因為這些指標型別之間沒有隱式轉換。
請注意,您沒有二維陣列。你有兩組一維陣列。
如果要使用,memcpy則需要使用回圈,例如
#include <string.h>
//...
for ( int i = 0; i < 6; i )
{
memcpy( board2[i], board1[i], 7 * sizeof( int ) );
}
在 for 回圈之后,兩組陣列將包含相同的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532244.html
