簡體   English   中英

嘗試將數組從stdin復制到2d數組時,為什么會出現分段錯誤?

[英]Why do I get a segmentation fault when trying to copy an array from stdin to a 2d array?

這是相對於HackerRank餐廳的問題,這是我在其他語言中已經解決了,但我想,現在,在C.解決https://www.hackerrank.com/challenges/restaurant

我首先嘗試將read_slice_dimension()的結果直接存儲到多維數組中,但是由於我無法在不使其靜態的情況下將其從函數傳遞回數組,因此這是行不通的,因為每個嵌套數組都指向同一靜態2整數數組在內存中,由於每次調用read_slice_dimension()read_slice_dimension()覆蓋該內存,這意味着我將擁有一個包含num_slices指針的數組, num_slices指針指向從stdin讀取的最后一個數組。

因此,我決定嘗試使用memcpy ,這樣我就可以將read_slice_dimension()read_slice_dimension()復制到新的內存塊中,以便它持久存在,並且在我讀取下一個切片時不會丟失。 但是,看來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] – user3386109

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM