2014-12-07 36 views
1

這是相對於HackerRank餐廳的問題,這是我在其他語言中已經解決了,但我想,現在,在C. https://www.hackerrank.com/challenges/restaurant爲什麼在嘗試將數組從stdin複製到2d數組時遇到了分段錯誤?

解決

我第一次嘗試將結果存儲如果read_slice_dimension()直接進入多維數組,但是因爲我不能將一個數組從一個函數傳遞回來而沒有將它設爲靜態,所以這不起作用,因爲然後每個嵌套數組指向內存中相同的靜態2整數數組,因此每次調用read_slice_dimension()時都會覆蓋它,意味着我會有一個數組包含​​指向從stdin讀入的最後一個數組的指針。

因此,我決定嘗試memcpy,這樣我可以在ARRY從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; 
} 
+0

'static int slice_dimension [2] = {0};'不是2維數組。 – zmb 2014-12-07 19:07:58

+0

@zmb該錯誤發生在'get_slices()'函數中,它試圖創建一個'slice_dimension'數組,它將是2D。 – josiah 2014-12-07 19:10:14

+4

你正在設置'slice = slices [i]',然後調用'malloc'。這是倒退。調用'malloc',然後設置'slices [i]'。 – user3386109 2014-12-07 19:12:25

回答

1

您'重新設置slice = slices[i],然後調用malloc。 '倒退。撥打malloc,然後設置slices[i]。 –   user3386109

相關問題