2013-05-13 98 views
2

我有形式的C- 結構:處理陣列

#define RGB_TYPE 1 
#define YUV_TYPE 2 
#define MAX_LIST 20 


typedef struct 
{ 
    uint16_t a[2]; 
    uint8_t b; 
    float_t c; 

} mystruct; 

我有MYSTRUCT的這樣

mystruct MyStructList[MAX_LIST]= { 
     {{100, 200}, RGB_TYPE, 25.0},   
     {{200, 400}, RGB_TYPE,25.0}, 
     {{300,600} ,YUV_TYPE ,30.0}, 
      {{400,600},YUV_TYPE, 30.0} 


}; 

在我的代碼執行以下操作的陣列;

mystruct config; 
int i = 0; 

..... 
for(i=0;i<4;i++) 
{ 
    config = MyStructList[i]; 
    /* further processing on config */ 
    some_func(i,&config); 

} 


int some_func(int x, mystruct* pstruct); 
{ 
     /* using pstruct values and storing them in internal arrays */ 
} 

這種結構複製和處理是否有效? 我正在使用mingw gcc

+0

'struct's是可賦值的,所以'config = MyStructList [i];'很好。還有其他疑問嗎? – 2013-05-13 19:21:54

+0

我沒有看到任何錯誤,但我不知道你的目標是什麼。你需要'配置'如果你要分配給其他'MyStructList [i]' 你可以做some_func(i,&MyStructList [i]) – hit 2013-05-13 19:25:28

+0

「使用pstruct值並將它們存儲在內部數組中」哪些內部數組是你存儲的pstruct值?當你說「pstruct values」時,你的意思是傳遞給'some_func'的指針還是指向'pstruct'結構的值? – 2013-05-13 19:37:25

回答

2

它看起來沒問題,但請注意config = MyStructList[i];會生成結構的淺表副本。如果你想對原始數組進行操作,mystruct應該是一個指針,它的地址是MyStructList [i]。

例如:

for(i=0;i<4;i++) 
{ 
    mystruct * config = &MyStructList[i]; 
    some_func(i, config); 
} 
0

與其說config = MyStructList[i];應分配使用malloc需要的元素的數量。例如,在循環體中,應該說

mystruct * config = (mystruct *) malloc (i * sizeof (mystruct)); 
some_func (i, config); // You do not have to use address because config is a pointer type now 
free (config); 
+0

** Dat kast to'mystruct *'!! ** – 2013-05-13 19:28:26

+2

(「你應該」 - 爲什麼他應該用這個方法?使用自動變量很好......) – 2013-05-13 19:29:11

0

這種副本是有效的。它可能效率不高,您可以在調用some_func()時使用指向原始結構的指針。然後,在some_func中,將其值存儲在內部數組中。