2013-11-25 24 views
0

在問爲什麼不能從malloc/calloc返回數組大小(我已收到對此的答案)之前,我已經問過一個與此有關的問題。在其他源文件中定義循環數組的問題

我目前的問題是我有2個數組定義,並填寫兩個單獨的源文件ship.c和rescue_assets.c。我試圖在名爲system_handler.c的文件內的一個方法中遍歷它們。

我遇到的麻煩是,這項任務要求您不要將數組大小硬化到代碼中,所以我沒有看到如何將每個c文件的數組大小鏈接到第3個c文件中的此函數。

最後,我想:

assign_mayday_to_ships(int SIZE_OF_ARRAY_FROM_FILE_1, int SIZE_OF_ARRAY_FROM_FILE_2){ 

    for(int i=0; i < SIZE_OF_ARRAYFROM_FILE_1; i++){ 
     for(int j = 0; < SIZE_OF_ARRAYFROM_FILE_2; j++{ 

      //do something 

     } 
    } 

我可以很容易地做到這一點,如果他們是在同一個文件,但我不能把來自兩個不同文件的方法,因爲它顯然缺乏所需的參數。

這裏是有問題的代碼(IVE只添加了必需的片段,所有的標題被包括和系統運行如預期條得到數組的大小):

system_handler.c

void assign_mayday_to_ships() { 

    mayday_call* mday_ptr; 
    ship* ship_ptr; 
    rescue_asset* assets_ptr; 

    mday_ptr = read_mayday_file(); 
    ship_ptr = read_ship_locations(); 
    assets_ptr = read_recuse_assets(); 

    int i; 
    int result; 

    /* loop through ship locations to find the ship that called the mayday 
    When found assign the mayday call to the ship for use when sending help*/ 
    for (i = 0; i < arr_size; i++) { 
     result = strncmp(mday_ptr->ais, (ship_ptr + i)->ais, COMPARE_LIMIT); 
     if (result == 0) { 
      mday_ptr->ship = (ship_ptr + i); 

     } 

    } 

    calc_distance_to_mayday(mday_ptr, assets_ptr); 

} 

rescue_asset .c:assets是我想要獲得大小的數組。

rescue_asset* assets; 

    no_of_lines = count_lines(locof); 
    printf("number of lines = %d \n", no_of_lines); 

    assets = calloc(no_of_lines,sizeof (rescue_asset)); 

ship.c:船是數組想要得到的大小。

ship* ships; 


    /* -1 because first line of file is not a ship location*/ 
    no_of_lines = (count_lines(locof) - 1); 

    ships = calloc(no_of_lines, sizeof (ship)); 

使用實際數組而不是calloc等是更好嗎?

謝謝, 克里斯。

回答

1

您必須將已分配的項目數量作爲參數傳遞給該函數。如果你不能這樣做(就像你在那些在被調用的函數中分配的情況那樣),你可以通過將大小作爲指針參數添加到執行分配的函數(通過引用傳遞)來返回它,或者返回包含指針和大小的結構。


對於第一種,你可以這樣做

size_t asset_size; 
asset *assets_ptr = read_recuse_assets(&asset_size); 

然後在read_recuse_assets設置*asset_size到正確的尺寸。

當然,你可以做相反的指針和大小,並傳遞一個指向assets_ptr作爲參數並返回大小的指針。

更完整的例子:

asset *read_recuse_assets(size_t *asset_size) 
{ 
    ... 

    *asset_size = no_of_lines; 
    return assets; 
} 

呼叫如上文所述。


對於第二個選擇,你可以有這樣的結構:

struct asset_data 
{ 
    size_t size; 
    asset *assets; 
}; 

然後填寫在該領域這種結構的返回實例(不是指針)

+0

多謝!我會選擇第一個選項,但是當我將size_t傳遞給read_rescue_assets(&asset_size)並在該方法內部時,我說:asset_size = no_of_lines它不更新assets_size的值,它保持爲某種愚蠢的大小!我更新了size_t行數的返回類型,但仍然沒有運氣:( –

+0

@chrisedwards由於您將它作爲指針傳遞(您必須通過C中的引用傳遞),因此您必須使用解除引用運算符該函數,就像'* asset_size = no_of_lines;' –

+0

@Joachin Pileborg謝謝,但是當我這樣做與上面的答案一起時,該值在方法內部正確設置,但後來當我在方法外打印它(所以如果我打印它在system_handler.c文件中)值不是他們應該的。任何想法? –