2012-05-21 134 views
0

我基本上試圖創建一個結構指針數組。這些指針中的每一個都應該指向同一結構數組的另一個元素,即BLOCKS [2]。結構指針數組

這是我迄今爲止所做的。

typedef struct bb { 
     .. 
     .. 
     .. 
    struct bb **successor; 
} BLOCK; 

BLOCK BLOCKS[10]; 

struct bb **A = malloc(sizeof(struct bb*)*5);  //create an array of pointers of type struct bb, 5 units i.e A[0]->A[4]. 

BLOCKS[0].successors = A       //just assigning 

現在......我該如何將指針數組A的第一個元素賦值給另一個結構?

我想:

A[0] = &BLOCKS[6]; 

它編譯罰款,但我得到了賽格故障。

+2

您是否嘗試過在調試器中運行程序? –

+1

它在哪裏發生故障? – hmjd

+0

它在「A [0] =&BLOCKS [6];」處發生故障。 – maxflow

回答

1

你有沒有試過這一個:

typedef struct bb { 
     .. 
     .. 
     .. 
    struct bb *successor; 
} BLOCK; 

BLOCK BLOCKS[10]; 

struct bb *A = malloc(sizeof(struct bb)*5);  //create an array of pointers of 
type struct bb, 5 units i.e A[0]->A[4]. 

BLOCKS[0].successors = A[0]; 

因爲看着它後迅速我覺得**應該呈現爲*和你的malloc是保留內存不能爲5層結構的大小,但5大小指向這個結構的指針。從問題

0

報價:基本上,我試圖創建結構指針數組。」

結構指針數組應該是

BLOCK *ptrBlockArr[10]; //This an array of size 10, which can store 10 pointers to the structure BLOCK 

現在,因爲,這些是指針,您將爲每個元素分配內存。這項工作應像

for(int i=0; i<10; i++) 
{ 
    ptrBlockArr[i] = (BLOCK *)malloc(sizeof(BLOCK)); 
} 

還包括問題:這些指針的每一個都應該指向同一個結構數組的另一個元素」。這可以像

for(int i=0; i<9; i++) // Run the loop till the last but one element 
{ 
    ptrBlockArr[i]->successor = ptrBlockArr[i+1]; 
} 
//Assign the last's element's sucessor as the first element. This will make it circular. Check if this is your intention 
ptrBlockArr[9]->successor = ptrBlockArr[0] 

來完成請注意,您在結構successorstruct bb**,而應該是struct bb*

此外,您可以優化代碼以將上面顯示的兩個循環合併爲一個循環。我會把它留給你自己學習和實施。

+0

抱歉,但這不符合我的代碼結構。我試圖創建一個結構指針的數組,也是每個結構的成員。 – maxflow