2016-07-30 50 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

相关问题