gpt4 book ai didi

C memcpy 交换二维数组的行

转载 作者:行者123 更新时间:2023-12-04 00:53:57 25 4
gpt4 key购买 nike

我正在尝试使用 memcpy C 库函数来交换二维数组(字符串数组)的行。此任务的源文件如下:

ma​​in.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;
}

ma​​in.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 - Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"? .

您可以修改指针的值以交换行。

void swap_rows(char **table, int r1, int r2) {
char* tmp;

tmp = table[r1];
table[r1] = table[r2];
table[r2] = tmp;
}

如果您更喜欢使用memcpy():

void swap_rows(char **table, int r1, int r2) {
char* tmp;
size_t size = sizeof(tmp);

memcpy(&tmp, &table[r1], size);
memcpy(&table[r1], &table[r2], size);
memcpy(&table[r2], &tmp, size);
}

关于C memcpy 交换二维数组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64184670/

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