2017-01-24 37 views
1

我正在處理的代碼需要雙精度的向量作爲輸入,我試圖通過在git上找到的this small library來使其大小可變。使用字符串代替雙打第一次迭代是:當讀取字符串時,內存覆蓋c

printf("Write vector components (type 'stop' to stop): \n"); 
int stop = 0; 
while (!stop) 
{ 
    fgets(c, sizeof(c), stdin); 
    if (strcmp("stop\n",c)!=0) 
    { 
     vector_add(&v, c); 
    } else { 
     stop = 1; 
    } 
} 

然而,當我打印出結果(例如具有3個輸入和「停止」),我得到

the vector is: stop stop stop

我曾嘗試每次輸入一個新組件時都會寫入第一個組件,結果是最後一個組件會覆蓋第一個組件(以及擴展,給出最終結果以及每個組件)。

但是,如果手動使用vector_add,則不會發生這種情況。例如,我曾嘗試從Git和我自己的代碼和完整的輸出相結合的例子是:

emil hannes lydia olle erik stop stop stop stop

所以讀取的時候僅覆蓋。我甚至無法理解正在發生的事情。 2年內沒有寫過C,我又重新開始了。

的完整代碼(不包括矢量圖庫):

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include "vector.c" 

void main(int argc, char* argv[]) { 
    char  c[20]; 
    vector  v; vector_init(&v); 


    printf("Write vector components (type 'stop' to stop):\n"); 
    int stop = 0; 
    while (!stop) 
    { 
     fgets(c, sizeof(c), stdin); 
     if (strcmp("stop\n",c)!=0) 
     { 
      vector_add(&v, c); 
      // printf("%s\n", (char*)vector_get(&v, 0)); 
     } else { 
      stop = 1; 
     } 
    } 


    printf("The vector is:\n"); 
    for (int i = 0; i < vector_count(&v); i++) { 
     printf("%s\n", (char*)vector_get(&v, i)); 
    } 

} /* main */ 
+1

您是否嘗試過通過符合調試通過代碼行步? –

回答

2

vector_add不復制數據,所以你的字符串仍保存在變量c。當你讀一個新的字符串時,它會覆蓋舊字符串。

如果字符串庫包含strdup,你可以試試這個:

vector_add(&v, strdup(c));