我正在处理的代码需要一个 double vector 作为输入,我试图通过使用 this small library 使其大小可变我在 git 上找到了。使用字符串而不是 double 的第一次迭代是:
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 个输入和“停止”),我得到了
vector 是:
停止
停止
停止
每次我输入一个新组件时,我都尝试编写第一个组件,结果是最后一个覆盖第一个(并且推而广之,给定最终结果,每个组件)。
但是,如果我手动使用 vector_add
就不会发生这种情况。例如,我尝试将 git 中的示例与我自己的代码结合起来,完整的输出是:
埃米尔
哈内斯
莉迪亚
奥莱
埃里克
停止
停止
停止
停止
所以它只在读取时覆盖。我什至无法开始理解正在发生的事情。已经 2 年没有编写任何 C 语言了,我正在重新开始。
完整代码(不包括 vector 库):
#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 */
最佳答案
vector_add
不会复制数据,因此您的字符串仍存储在变量 c
中。当您读取新字符串时,它会覆盖旧字符串。
如果你的字符串库包含strdup
,你可以试试这个:
vector_add(&v, strdup(c));
关于c - 在c中读取字符串时内存覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41835723/