gpt4 book ai didi

c - 为什么在尝试将数组从标准输入复制到二维数组时出现段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:35 25 4
gpt4 key购买 nike

这与 HackerRank Restaurant 问题有关,我已经用其他语言解决了这个问题,但现在正在尝试用 C 来解决。https://www.hackerrank.com/challenges/restaurant

我首先尝试存储结果 if read_slice_dimension()直接进入多维数组,但是因为我不能在不将数组设为静态的情况下将数组从函数传回,所以这是行不通的,因为每个嵌套数组都指向内存中相同的静态 2 整数数组,结果是每次都被覆盖read_slice_dimension()被称为,意味着我将有一个包含 num_slices 的数组指向从标准输入读入的最后一个数组的指针。

因此我决定尝试 memcpy , 这样我就可以从 read_slice_dimension() 复制 arry到一个新的内存块,以便它在我读取下一个切片时持续存在并且不会丢失。然而,似乎memcpy不是这样做的方法。什么是?

// Gets the number of slices for this test according to the first input value from stdin.
int read_num_slices() {
int num_slices = 0;

scanf("%i", &num_slices);

if (num_slices == 0) {
goto error;
}

return num_slices;

error:
flag_error("ERROR: Could not parse the number of entries from first input line.");
}

// Gets a single line from stdin and attempts to parse it into a 2D int array representing the dimensions of a slice.
int* read_slice_dimension() {
static int slice_dimension[2] = {0};

scanf("%i %i", &slice_dimension[0], &slice_dimension[1]);

if (slice_dimension[0] + slice_dimension[1] == 0) {
goto error;
}

return slice_dimension;

error:
flag_error("ERROR: Could not parse line entered into a 2 integer array representing the slice's dimensions.");
}

// Gets all of the bread slices to be processed.
//
// This function reads from stdin. The first line should be a single integer that specifies the number of slices to be
// processed by this current test. The subsequent lines should be two integers separated by a space which represent
// the 2D dimensions of each slice.
int** get_slices() {
int num_slices = read_num_slices();
static int** slices;
slices = (int**)malloc(num_slices * sizeof(int*));

int i = 0;
for (i; i < num_slices; i++) {
int* slice = slices[i];
slice = (int*)malloc(2 * sizeof(int));
memcpy(slice, read_slice_dimension(), 2 * sizeof(int));
printf("%i %i\n", slices[i][0], slices[i][1]); // CAUSES SEGMENTATION FAULT
}

return slices;
}

最佳答案

您正在设置 slice = slices[i],然后调用 malloc。那是倒退。调用malloc,然后设置slices[i]。 – 用户 3386109

关于c - 为什么在尝试将数组从标准输入复制到二维数组时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27346616/

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