2016-07-30 48 views
0

目的我的程序的簡單,從文件中讀取INT數字序列,這裏的代碼:傳遞一個未初始化的數組的函數用C

int main() 
{ 
    FILE *file = fopen("test.txt", "r"); 

    int *array = NULL; // Declaration of pointer to future array; 
    int count; 

    process_file(file, array, &count); 

    return 0; 
} 

// Function returns 'zero' if everything goes successful plus array and count of elements as arguments 
int process_file(FILE *file, int *arr, int *count) 
{ 
    int a; 
    int i; 
    *count = 0; 

    // Function counts elements of sequence 
    while (fscanf(file, "%d", &a) == 1) 
    { 
     *count += 1; 
    } 

    arr = (int*) malloc(*count * sizeof(int)); // Here program allocates some memory for array 

    rewind(file); 

    i = 0; 
    while (fscanf(file, "%d", &a) == 1) 
    { 
     arr[i] = a; 
     i++; 
    } 

    fclose(file); 

    return 0; 
} 

問題是,在外部函數(主),陣列沒有改變。 它怎麼能被修復?

回答

4

您需要通過引用傳遞數組,以便該函數可以更改其調用者的數組。

它必須是:

process_file(FILE *file, int **arr, int *count) 

,並呼籲像這樣:

process_file(file, &array, &count); 

此外,我建議:

+1

不應該是「* array = malloc(* count * sizeof ** array);」? –

+0

謝謝,它適用於一些調整:在函數中爲數組的元素賦值,需要使它像這樣(* array)[i] = value – JacobLutin

相關問題