正如聲明,您已經創建Element
實例的5個元素的數組;無需分配新的Element
對象。你可以繼續讀/分配每個元素的每個成員:
element[i].value = some_value();
strcpy(element[i].someString, some_string());
如果你想向模仿Java方法,你會做類似如下:
Element *elementList[5]; // create elementList as an array of *pointers* to Element
...
elementList[i] = malloc(sizeof *elementList[i]); // dynamically allocate each element
注意在這種情況下,你會使用->
運營商,而不是運營商.
訪問每個Element
成員,因爲每個elementList[i]
是指針到Element
,不是Element
斯塔nce:
elementList[i]->value = some_value();
strcpy(elementList[i]->someString, some_string());
無論哪種情況,數組大小都是固定的;您無法增大或縮小陣列中元素的數量。
該數組的每個部分*已經是一個元素。你不需要做「新」,內存已經被分配,並且'elementList [1]'可以被直接尋址(儘管它可能包含垃圾,除非你初始化它......) – tucuxi