【发布时间】:2017-09-10 05:41:50
【问题描述】:
首先,我知道三重和四重指针是不好的做法而且很丑陋,这不是这个问题的重点,我试图了解它们是如何工作的。我知道使用结构会好得多。
我正在尝试编写一个函数,该函数使用 memmove() 和 memcpy() 对通过引用传递的三重和双指针(或 C 版本)执行一些内存操作。我的memmove() 工作正常,但memcpy() 产生SIGSEGV。这是一个最小的例子
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define UNDO_DEPTH 25
void boardSave(int ***board, int game_sz, int ****history) {
// Shift history to the right
memmove(*history + 1, *history, (UNDO_DEPTH - 1) * sizeof(**history));
// Copy board into history
for (int row = 0; row < game_sz; ++row) {
memcpy((*history)[0][row], (*board)[row], game_sz * sizeof((**board)[row]));
}
}
int main(){
// Game
int game_sz = 5;
// Allocate array for the board
int **board = calloc(game_sz, sizeof(int *));
for (int i = 0; i < game_sz; ++i) board[i] = calloc(game_sz, sizeof(int));
// Allocate array for the history
int ***history = calloc(UNDO_DEPTH, sizeof(int **));
for (int i = 0; i < UNDO_DEPTH; ++i) {
history[i] = calloc(game_sz, sizeof(int *));
for (int j = 0; j < game_sz; ++j) {
history[i][j] = calloc(game_sz, sizeof(int));
}
}
board[0][0] = 1;
boardSave(&board, game_sz, &history);
}
这里boardSave()的目的是将board复制到history[0]上。我究竟做错了什么?为什么这会导致分段错误?
【问题讨论】:
-
memmove(**history + 1, *history,... 中不同的间接深度相当可疑。 -
@aschepler 我的意图是移动
history1“槽到右边”的所有元素,消除最后一个(在本例中为第 25 个)元素。 -
memmove(**history + 1, **history, (UNDO_DEPTH - 1) * sizeof(***history));似乎修复了它。需要多发短信 -
请注意,称某人为Three Star Programmer 不是一个批准条款。四星程序员可能更不受欢迎。我的思绪被震撼了;我不想维护你的代码。
-
是的;我要让其他任何出现并发现这一点的人都知道你在深水中,问题并不令人惊讶。你最好不知道,IMO。
标签: c pointers pass-by-reference indirection