2017-01-24 33 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));