2013-03-23 34 views
0

對不起,我花了大部分時間試圖解決什麼可能是一個簡單的指針問題,想知道是否有人可以提供幫助。如何使用指針間接地從函數返回(動態分配的)數組?

我想要一個函數,它返回一個數字和一個數組到main(),因此至少需要使用其中的一個指針。該數組必須在函數內動態分配。

我試圖在下面以簡化形式展示我的最佳嘗試。我只是得到「分段錯誤」。

double my_func(double **ptr); 

int main(int argc, char **argv){ 
    double value; 
    double *a; 
    value = my_func(&a); 

    printf("Value is %f array[1] is %f \n", value, a[1]); 
    return 0; 
} 

double my_func(double **ptr){ 
    int i; 
    /* generate an array */ 
    void *memory = malloc(10*sizeof(double)); 

    if (memory == NULL){ 
    printf("ERROR: out of memory\n"); 
    } 

    *ptr = (double *) memory; 


    /* Fill the array with some values */ 
    for (i=0;i<10;i++) 
    { 
    **(ptr+i) = 42; 
    } 


    return 3.14; 
} 

[這樣做的原因是,我有一個函數,在一個文件中讀取,並我想返回的行數和包含該文件的內容到主陣列()。我希望它動態分配數組,以便該程序將適用於任何大小的文件。]

感謝您的幫助!

+1

所有三個答案都非常有幫助,謝謝大家! – user1725306 2013-03-24 18:31:59

回答

1

以下行要添加我的變量a的地址:

**(ptr+i) = 42; 

要我添加到您需要取消引用PTR第一malloced地址:

*(*ptr+i) = 42; 
0

除了@ ygram的答案,我覺得它有助於通過使用一個輔助變量來簡化在分配功能(my_func中的例子)的東西:

double myfunc(double **a_dp) { 
    int i; 
    double *dp; 

    dp = malloc(10 * sizeof *dp); 
    /* no cast required for malloc in C, but make sure you #include <stdlib.h> */ 

    if (dp == NULL) { 
     ... handle error ... 
    } 

    *a_dp = dp; 

    for (i = 0; i < 10; i++) 
     dp[i] = 42; 

    return 3.14; 
} 

也就是說,而不必重複寫*(*ptr + index)(*ptr)[index],您創建一個保存你也將存入*ptr,尤其是圓形我稱之爲局部變量dp - 然後你只需要使用dp本地,除了值的局部變量(一個,或者有時幾個)地方,您必須存儲該值,以便您的呼叫者接收它。

0

數組和數字之間的關係是什麼?爲了簡單起見,把它們放在一個結構中不是更好,它真的有助於清理這裏的東西。

typedef struct ArrayStruct { 
    double num; 
    long len; // ideal place to store the array length for future bounds checking! 
    double *array; 
} ArrayStruct; 


int main(int argc, char **argv) { 

    ArrayStruct myArray = {0}; 
    myFunc(&myArray); 

    printf("Value is %f array[1] is %f \n", myArray.num, myArray.array[1]); 

    free(myArray.array); 
    return 0; 
} 


void myFunc(ArrayStruct *s) { 

    // Do whatever you like with the struct: 
    s->len = 10; 
    s->array = (double *)malloc(s->len * sizeof(double)); 

    for (int i=0; i< s->len; i++) 
     s->array[1] = 42; 

    s->num = 3.14; 
} 

這樣做,這樣意味着你不必擔心返回任何東西或用指針搞亂,只是聲明瞭結構主,傳遞一個參考myFunc()或任何你想要使用它,然後改變您認爲合適的數據。

對不起,如果在代碼中有任何錯誤,只需快速輸入它,但它應該說明這一點!