2013-02-16 86 views
0

我使用基於C的網絡模擬器OPNET。在我的一個C文件(稱爲進程模型)中,我有一個全局可訪問的鏈表(稱爲obstacle_list )。在下面的代碼中,我用包含字符串的較小列表填充它。這似乎工作得很好,我可以在最後回讀整個列表。列表(內部列表被刪除或釋放內存)

但是我需要在稍後的時間從另一個C文件(進程模型)訪問這個全局列表。

當我嘗試訪問這個全局鏈表時,我可以看到它包含380項(正確),但是當我嘗試訪問內部鏈表時,它們是空的。

當我第一天填充列表時,它必須是內存分配監督。當我使用行「input = op_prg_list_create()」創建內部列表並使用strdup爲列表內容分配內存時,我不明白爲什麼會發生這種情況。

我很困擾這個,所以任何幫助或指針,可能會發生什麼將不勝感激。

非常感謝。

fgets(line, sizeof(line), obstaclePositions_traj_file); 

obstacle_list = op_prg_list_create(); 

while (line != OPC_NIL) 
{ 
token = strtok(line, "\t\n"); //Pull the string apart into tokens using the \t 
input = op_prg_list_create(); 

while (token != NULL) 
     { 
      test_token = strdup(token); 

      if (op_prg_list_size(input) == 0) 
      op_prg_list_insert(input,test_token,OPC_LISTPOS_HEAD); 
      else 
      op_prg_list_insert(input,test_token,OPC_LISTPOS_TAIL); 
     token = strtok (NULL, "\t\n"); 
     }  

     if (op_prg_list_size(obstacle_list) == 0) 
    op_prg_list_insert(obstacle_list,input,OPC_LISTPOS_HEAD); 
    else 
    op_prg_list_insert(obstacle_list,input,OPC_LISTPOS_TAIL); 

} 


//check the list has been populated correctly below (it has) 

/*size_ob_list = op_prg_list_size (obstacle_list); 
for (k = 0; k <size_ob_list; k++) 
{ 
line_coord_list = (List*)op_prg_list_access (obstacle_list, k);  
count_inner_list = op_prg_list_size (line_coord_list); 
for (j=0; j< count_inner_list; j++) 
{ 
    coords = (char*)op_prg_list_access (line_coord_list, j); 
    printf("%c", coords);  
} 
}*/ 

回答

0

while (line != OPC_NIL) {}是可疑的。

在EOF,與fgets()回報空,但不改變緩衝區(最後succesfull調用的內容仍然會在那裏)

obstacle_list = op_prg_list_create(); 

while (fgets(line, sizeof(line), obstaclePositions_traj_file)) 
{ 
    input = op_prg_list_create(); 

    for(token = strtok(line, "\t\n"); token ; token = strtok (NULL, "\t\n")) 
     { 
      test_token = strdup(token); 

      op_prg_list_insert(input,test_token 
      , (op_prg_list_size(input)==0) ? OPC_LISTPOS_HEAD : OPC_LISTPOS_TAIL 
      ); 
    }  

    op_prg_list_insert(obstacle_list,input 
    , (op_prg_list_size(obstacle_list) == 0) ? OPC_LISTPOS_HEAD : OPC_LISTPOS_TAIL 
    ); 

} 
+0

嗨Wildplasser,感謝您的幫助。我已經測試過它,但它似乎只爲每個內部列表插入一個字符串。我的文件將包含一個字符串列表:203.14,123.25,後跟一個標籤,後面跟着另一個數字對。每行數量對數量不等。上面的解決方案只循環一次for循環。我嘗試將中間狀態從標記更改爲sizeof(行),但它顯示「行」更改爲令牌的內容與行「標記= strtok(行,」\ t \ n「);」。有任何想法嗎? – user2050990 2013-02-16 15:10:25

+0

糟糕,我忘記刪除您的第一個預讀strtok()調用(在循環之前)。修復。 – wildplasser 2013-02-16 15:17:59

+0

它現在正在工作(比我的第一個解決方案更整潔,所以謝謝你),但不幸的是它並沒有解決原來的問題!當我嘗試從另一個C進程模型訪問它時,內部列表是空的(但它可以在全局障礙列表中看到size = 380)。唯一能想到的是,obstacle_list被定義爲「List * obstacle_list;」在全局頭文件中。也許我應該在頭文件中實際創建列表(使用op_prg_list_create())?或者內部列表也需要全球化? – user2050990 2013-02-16 15:25:44