2013-10-12 36 views
0

我有一個列表。列表中的每個元素都是一個結構體。如何使指向指向列表中的每個成員的指針

struct A 
{ 
    int size; 
} 

的數據是這樣的:

list[0]->size = a number. 

我如何分配一個指針到列表中的每個成員?

int *p; 
for(i = 0; i < listSize; i++) 
{ 
    p = &list[i]; 
} 

這不起作用,因爲我只分配一個指針到列表的最後一個元素。我應該製作一個指針列表嗎?

這應該解決XY問題。 如何爲列表中的每個元素創建指針?

編輯: 表看起來是

A **list; 

我想通過指針,而不是通過結構來進行排序,以便它更快。

現在正在試圖這樣:

A ***p = (A***) malloc(sizeof(A***)); 

for(i = 0; i < listLength; i++) 
    p[i] = &list[i]; 

for(i = 0; i < listLength; i++) 
    printf(p[i]->size); // Error. 
+1

這聽起來像一個典型的[XY問題(HTTP://meta.stackexchange .COM /問題/ 66377 /什麼,是最XY-問題)。你想完成什麼? – Pankrates

+0

'list [i]'已經是一個指向每個元素的指針。你問的是錯誤的問題。 – gcochard

+0

我不禁注意到,您的示例結構沒有鏈接成員指向列表中的下一個結構實例。沒有鏈接指針的地方,你沒有鏈接列表。這是你問的嗎? - 可能不是你似乎在使用數組,而不是鏈接列表,但是你又沒有'malloc'd內存的上述數組 - 你似乎正在使用一個未初始化的指針,就好像它是一個數組。 – Steve314

回答

0
typedef struct { 
    int size; 
} A, *pA; 

typedef struct { 
    int size; 
} B, *pB; 

//and so on... 

//Now your list can be a collection of these 
typedef struct { 
    A a; 
    B b; 
    //additional members if defined 
} LIST; 

LIST list[20], *pList; //[edited to make array of LIST] 
//prototype List function 

LIST * updateList(LIST *a); 

int main(void) 
{ 
    pList = &list[0]; //[edit to init pointer to array of lists 
    //access and use pointers to list as necessary 
    LIST *b = updateList(pList); 
    //Use the updated list here 
    printf("b[0].a.size is: %d\n" , b[0].a.size); 
    printf("b[1].a.size is: %d\n" , b[1].a.size); 
    printf("b[2].a.size is: %d\n" , b[2].a.size); 
    printf("b[3].b.size is: %d\n" , b[3].b.size); 
    printf("b[4].b.size is: %d\n" , b[4].b.size); 
    printf("b[5].b.size is: %d\n" , b[5].b.size); 

    return 0; 
} 

LIST * updateList(LIST *a) 
{ 
    //do some manipulations to LIST here... 
     a[0].a.size=1; 
     a[1].a.size=2; 
     a[2].a.size=3; 
     //and so on. 
     a[3].b.size=4; 
     a[4].b.size=5; 
     a[5].b.size=6; 
     //and so on. 
    return a; 
} 

將這項工作的嗎?

+0

我認爲你在做別的事情。我只需要p0 ... pn列表中每個元素的指針[0..n] –

+0

定義了一個LIST數組。 'LIST list [20],pList;'然後'pList =&list [0];'。新增了一個指針,用於列表數組中的每個元素。我可能完全忽略了這一點,但是這個架構應該支持一個結構成員指針數組。如果我錯過了這個觀點,請給出更多的線索。有時我可以變厚:)(見編輯答案) – ryyker

+0

邁克,(從上面的評論重複)看看*** [這裏](http://stackoverflow.com/a/522067/645128)***看起來像什麼一個很好的例子。你是對的,在那個人把它拿下來之前有一個很好的例子,@ Micheal.yxd也正在成爲一個很好的例子。你也是對的,因爲我不在正確的道路上。贏一些,輸一些。祝你好運! – ryyker

1

您可以創建一個類似指針數組: struct A *arr_pointer[N]

基本上,你鏈接結構應該喜歡:

struct A { 
    int size; 
    struct A *next; 
}; 
+0

您已經確定了正確的概念,我相信這是符合OP要求的基礎。 [看這裏](http://stackoverflow.com/a/522067/645128) – ryyker