2013-02-25 36 views
1

的變化大小我有一個結構:傳遞結構的陣列,以函數數組

struct Thing { 
    int id; 
} 

然後,我創建的Thing秒的數組:

struct Thing *a; 
a = (struct Thing *) malloc(sizeof(struct Thing)); 
a->id = 1; 

struct Thing *b; 
b = (struct Thing *) malloc(sizeof(struct Thing)); 
b->id = 2; 

struct Thing *array[] = {a,b}; 

我檢查陣列的大小和是 我檢查陣列的大小:

printf("%d",sizeof(array)/sizeof(array[0])); 

我也有一個函數, S IN事物的數組:

void function(struct Thing *array[]) { 
    //do stuff 
} 

然後我通過數組中發揮作用:

function(array); 

在這個函數中,數組的大小爲1 可有人點我放哪兒我出錯了,爲什麼數組1中的數組的大小?

+0

請閱讀C常問問題http://www.c-faq.com/aryptr/index.html – 2013-02-25 07:41:54

+0

或[什麼是陣列衰減?](http://stackoverflow.com/q/1461432) – 2013-02-25 07:45:18

+0

@ KarthikT我在下面的評論中找到了張遠的解決方案。 – drum 2013-02-25 08:10:36

回答

2

當您將任何類型的數組傳遞給函數時,它將衰減爲指向此數組的第一個元素的指針。

void function(struct Thing *array[]) { 
    //do stuff 
} 

僅僅是

void function(struct Thing** array) { 
    //do stuff 
} 
+0

這解釋了爲什麼只有第一個元素仍然存在。 – drum 2013-02-25 07:41:35

+0

@drum,兩個元素仍然存在,第二個元素可以作爲'array [1]'訪問。只是數據類型已經從數組改變爲指針,並且因此具有「sizeof」的行爲。 – 2013-02-25 07:42:49

+0

不,這兩個元素都保留,但指針僅指向數組的開頭!您應該可以在不使用SEGFAULT的情況下訪問函數中的第二個索引。 – 2013-02-25 07:43:01

1

您的數組定義語法糖

struct Thing *array[] = {a,b}; 

應該

struct Thing array[] = {a,b}; 

然後將它傳遞給函數;該函數應該聲明爲

void function(struct Thing *array, int count) { 
//do stuff 
} 

所以你可以傳遞數組的邊界。

+2

'a'和'b'是指向struct的指針,並且您建議使用指向結構的指針初始化一個結構數組,如何工作? – 2013-02-25 07:48:15

+1

'struct Thing array [] = {* a,* b}'; – yuan 2013-02-25 07:54:17

+0

@張元:謝謝!這正是我的問題的解決方案!你應該發佈答案,我會接受它。 – drum 2013-02-25 08:00:44