2016-02-04 133 views
-3

我在C.如何通過引用傳遞一個數組中的函數?

我有以下代碼初學者編碼器:

int main() 

{ 

struct* Array[malloc(10*sizeOf(struct)]; 
    /* I then fill the struct. (int num,float points) 
    * I then want to pass this array that I've filled up to a sortList function, 
    * which then outputs the sorted array back to main(). 
    * 
    * Then I want to output the array as: "number, points" */ 
} 

struct struct 
{ 
int number; 
float points; 
} 

void sortList() 
{ 
    /*sort Array, then return sorted array*/ 
} 

我將如何傳遞數組,然後回來?

任何鏈接或建議都非常有幫助。

+1

'結構*數組[malloc的(10 *整型尺寸(結構)];'哪種語言 –

+2

'結構*數組[malloc的(10 *整型尺寸(結構)〕;'這是什麼有人教' malloc()'今天錯了,第二篇文章有這樣一個嚴重問題 –

+0

這是C.對不起,這就是我學會如何分配內存給一個有10個條目的數組! – starter1011

回答

2

如何通過引用傳遞數組...?

當一個數組a被傳遞給函數foo(a),它是實際參數。在C中,當數組傳遞給一個函數,而不是整個數組被賦予foo()時,表達式a被轉換爲數組第一個元素的地址。

除了當它是sizeof操作者的操作數時,_Alignof操作者,或一元&操作者,或者是用於初始化數組文本的字符串,其具有輸入「」類型的陣列'的表達式被轉換爲一個表達式,其類型爲'指向類型''的指針指向數組對象的初始元素,而不是左值。 ... C11dr§6.3.2.13

所以foo()被賦予一個地址int *。讓我們假設值爲1234

功能void foo(int *fa)內部,形式參數fa取值爲1234

從呼叫者的角度來看,這是通過參考,因爲afoo()的影響,並且該函數收到「參考」。從功能的角度來看,這是通過價值,因爲fa獲得轉換後的a的副本。在C中,當人們說C沒有通過引用傳遞任何東西時,通常會提到這種第二種觀點。在這兩種情況下,faint *而不是數組。

foo()在變量fa中的地址爲maina。所以代碼fa[0] = 456設置了一個值,該值在foo()完成後仍然可見。

void foo(int *fa) { 
    fa[0] = 456; 
} 

int main(void) { 
    int a[5]; 
    a[0] = 123; 
    printf("%d\n", a[0]); // prints 123 
    foo(a); 
    printf("%d\n", a[0]); // prints 456 
    return 0; 
} 

我用一個簡單int陣列來解釋的東西。然而原始代碼還有其他問題。下面是如何分配內存的想法。

// struct* Array[malloc(10*sizeOf(struct)]; 
struct ok12type* ok12Array = malloc(sizeof *ok12Array * 10); 
.... 
// Do stuff with ok12Array 
... 
free(ok12Array); 
ok12Array = NULL; 
// Do _not_ do stuff with ok12Array 
0

代碼似乎是錯誤的。在C中,數組總是按引用傳遞。

0

首先你應該命名你的結構。我在下面的例子中給它起了名字typename

分配內存,你想:

struct typename *Array = malloc(10*sizeof(struct typename)); 

數組傳遞給函數很容易,只需要聲明你的函數爲:

void sortList(struct typename *Array) 
{ 
} 

然後,您可以在陣列上直接運行該函數,因爲數組總是通過引用傳遞,絕不傳遞值。

所以,你的程序可能看起來像:

struct typename 
{ 
    int number; 
    float points; 
} 

int main() 

{ 

    struct typename *Array = malloc(10*sizeof(struct typename)); 
    Array[0].number = 5; 
    Array[0].points = 7; 
    Array[1].number = 2; 
    Array[1].points = 11; 

    /* Fill the rest of the array. */ 

    /* Sort it. */ 
    sortList(Array); 
} 



void sortList(struct typename *Array) 
{ 
    /* Do your sorting here. */ 
}