这与HackerRank餐厅问题有关,我已用其他语言解决了这个问题,但我现在正尝试用C解决。https://www.hackerrank.com/challenges/restaurant
我首先尝试将结果read_slice_dimension()
直接存储到多维数组中,但是因为我无法在不使其静态的情况下从函数传回数组,所以这不起作用,因为每个嵌套数组都指向内存中相同的静态2整数数组,由于每次调用read_slice_dimension()
时都会被覆盖,这意味着我将有一个数组包含指向从stdin读入的最后一个数组的num_slices
个指针。< / p>
因此我决定尝试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;
}
答案 0 :(得分:1)
您正在设置slice = slices[i]
,然后调用malloc
。那是倒退。致电malloc
,然后设置slices[i]
。
- user3386109