【发布时间】:2020-10-03 13:12:07
【问题描述】:
我正在尝试使用memcpy C 库函数来交换二维数组(字符串数组)的行。此任务的源文件如下:
main.c
#include <stdlib.h>
#include "main.h"
char *table[NBLOCK] = {
"abcdefghi",
"defghiabc",
"ghiabcdef",
"bcaefdhig",
"efdhigbca",
"higbcaefd",
"cabfdeigh",
"fdeighcab",
"ighcabfde",
};
int main() {
swap_rows(table, 0, 2);
return 0;
}
main.h
#define NBLOCK 9
#define BLOCK_CELLS 9
void swap_rows(char**, int, int);
shuffle.c
#include <string.h>
#include "main.h"
void swap_rows(char **table, int r1, int r2) {
char tmp[BLOCK_CELLS];
size_t size = sizeof(char) * BLOCK_CELLS;
memcpy(tmp, table[r1], size);
memcpy(table[r1], table[r2], size); /* SIGSEGV here */
memcpy(table[r2], tmp, size);
}
swap_rows 函数内部发生分段错误。在上面显示的三个memcpy 调用中,第一个调用按预期工作。我注释掉了最后两个 memcpy 调用并添加到以下行:
table[0][0] = 'z';
但是,分段错误再次发生。为什么我不允许在 swap_rows 函数中覆盖 table 的值?
【问题讨论】:
标签: c pointers segmentation-fault