c - C String 数组中的每个值都等于最后添加的值
问题描述
我正在尝试使用文本行分析数据文件,然后使用 while 循环将文本行添加到字符串数组中。似乎每次我在索引处向数组添加新行时,索引中低于它的每个值都设置为正在添加的字符串。例如,如果我将 strings[2] 设置为值“foo”,它也会将 strings[1] 和 strings[0] 设置为“foo”,即使 strings[1] 和 strings[0] 的值不同前。
我尝试过测试,看看我添加到数组中的值是正确的,而且它们是正确的。我也尝试过将数组设为 const,但没有成功。
int main()
{
char** strings = malloc(1000 * sizeof(char));
int index = 0;
StringBundle** bundle = malloc(1000 * sizeof(StringBundle)); //StringBundle is used to parse the string
while (fgets(str, 500, file))
{
bundle[index] = createStringBundle(str); //String bundle works correctly
char** tokens = bundle[index]->Tokens; //Gets the parts of a parsed string
char concat[100]; //This string is composed of two parts of the string that is parsed
strcpy(concat, tokens[1]);
strcat(concat, tokens[3]);
printf("%s\n", concat) //This will print the correct value, so the value of concat is correct
strings[index] = concat;
index++;
}
//"Montery CA" is the last value added to the array
printf("%s\n", strings[2]); //Issue- this will print "Montery CA", when it should print "Chicago IL"
printf("%s\n", strings[13]); //Issue- this will print "Montery CA", when it should print "San Diego CA"
}
解决方案
推荐阅读
- tcl - 如何以图形方式表示 Tcl 代码输出?
- python - 如何使用 python 更新、旋转和显示 ply 文件?
- javascript - 如何用 null 代替严格类型的测试方法参数 javascript
- c# - 编译器如何知道在等待调用后在哪里恢复控制
- bash - bash:使用动态名称打印动态变量
- reactjs - Clear Ref in useEffect Cleanup
- reactjs - TypeError:无法读取未定义的属性“getParam”。使用 jest 和酶反应原生单元测试?
- ios - 在 swift 中将错误转换为 NSRoor (_swift_stdlib_bridgeErrorToNSError) 时崩溃
- laravel - Laravel 并在占位符中显示错误
- javascript - 在 JavaScript 中将 N 个未排序数组合并为 1 个排序数组的最快方法是什么?