c++ - 为什么这个程序告诉我传递了无效参数?
问题描述
老实说,我什至不知道我现在想要做什么。但是在我让这个函数工作之前我不能更进一步,它每次都会抛出那个异常,出了什么问题?异常是“CS 330 19S、P1、Calvert、Program 1.exe 中 0x0F61CAB6 (ucrtbased.dll) 处的未处理异常:将无效参数传递给认为无效参数致命的函数”
#include<iostream>
#include<vector>
#include <fstream>
using namespace std;
struct Kinematic {
vector<vector<float>> position;
float orientation;
vector<vector<float>> velocity;
float rotation;
};
struct StreeringOutput {
vector<vector<float>> linear;
float angular;
};
void update(StreeringOutput steering, float time, Kinematic k)
{
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
k.position[i][j] += k.velocity[i][j] * time +
0.5*steering.linear[i][j] * time*time;
//the above command is where it throws the exception
k.velocity[i][j] += steering.linear[i][j] * time;
}
}
k.orientation += k.rotation*time + 0.5*steering.angular*time*time;
k.rotation = steering.angular*time;
}
int main()
{
int test;
Kinematic kin;
StreeringOutput steering;
float time = 0.0;
ofstream outfile;
outfile.open("Output.txt");
for (int i = 0; i < 100; i++)
{
update(steering, time, kin);
time += 0.5;
}
cin >> test;
return 0;
}
解决方案
当程序启动时,您创建对象:
Kinematic kin;
StreeringOutput steering;
这称为默认初始化,即所有成员都被初始化为默认值。对于vector
,它是空状态。
但是update
做这些事情:
// i and j can be as large as 99
k.position[i][j]
k.velocity[i][j]
steering.linear[i][j]
但是position
,等都是空的!vector
s 不能自动增长以满足您的需求。您正在索引out-of-bound,这是未定义的行为。
您应该正确初始化向量以确保实际上有 100 个元素:
Kinematic kin;
kin.position.assign(100, vector<float>(100));
// same for others
推荐阅读
- angular - 如何在垫表上显示几行的编辑图标
- javascript - 如何根据 id 使用另一个嵌套数组对嵌套数组对象进行排序?
- c# - 身份服务器 OpenID 配置 Http 重定向
- cross-browser - 如何为边缘应用样式?
- react-native - 返回时 react-native Redux 更新状态
- laravel - 如何在树多对多表之间创建关系?
- mysql - 在具有 3 个表的 mysql 中查找不匹配的记录
- mysql - MySQL中的模式VS表VS列CHARSET有什么区别?
- wordpress - 如何知道 WooCommerce REST API 中哪个产品变体具有哪个变体 ID
- db2 - 是否建议或可以同时在两个不同的物理文件上运行 RGZPFM?