gpt4 book ai didi

c++ - 将字符串中的 float 放入 void 数组

转载 作者:太空宇宙 更新时间:2023-11-03 10:20:28 25 4
gpt4 key购买 nike

当我的函数从字符串中读取 float 并将它们放入空数组中时,我遇到了段错误。段错误发生在以下代码中 for 循环的大约 200 次迭代之后:

// Allocate memory
void** data;
data = (void**)malloc(num_vals * sizeof(float));

// Convert text to floats
(*(float**)data)[0] = atof(strtok(text, " "));
for(int index=1; index<num_vals; index++) {
(*(float**)data)[index] = atof(strtok(NULL, " "));
std::cout << (*(float**)data)[index] << std::endl;
}

void 数组是必需的,因为字符串中数据的大小和类型是在运行时确定的。我试过增加 malloc 的大小,但它没有任何改变。有什么想法吗?

最佳答案

认真的??

std::vector<float> data;
std::istringstream str(text);
float fv;
while (str >> fv)
{
data.push_back(fv);
}

现在是c++

关于c++ - 将字符串中的 float 放入 void 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7349087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com