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

标签 c gcc multidimensional-array segmentation-fault

这与 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/

相关文章:

linux - 如何删除共享库中符号周围的字符?

gcc - 如何在 GCC Linux 中指定非默认共享库路径?运行时获取 "error while loading shared libraries"

python - 如何从 (1000, 1) 和索引槽 n 值创建 (1000, 500) 数组?

c - 将 C 数组拆分为 n 个相等的部分

c - 两个进程之间的命名共享内存

这个令人困惑的 typedef 的 C 语言问题

c - 如何用C多次写入一个文件?

编译带有依赖项、h 和 h0 文件的 c 程序

javascript - 如何按第二个数组降序对多维数组进行排序?

c - 声明多维数组 : Pointer or Array Definiton