存储到阵列的问题
issues with Storing to array
>我正在测试我的一个类,但由于某种原因,我似乎无法将 intiger 从 2d 数组转换为双倍。这是我的(非常简化的)代码:主要.cpp
#include<iostream>
#include<conio.h>
#include<string>
#include "trajectories.h"
int main()
{
std::string response;
int numOfCoords;
int speed;
int ** coords;
std::cout<<"enter the number of coordinates: ";
std::cin>>numOfCoords;
std::cout<<"enter speed: ";
std::cin>>speed;
coords=new int *[numOfCoords];
for (int i=0; i<numOfCoords; i++)
coords[i] = new int[2];
for(int i=0; i<numOfCoords*2; i++)
{
if(i%2==0)
std::cout<<"enter point "<<i/2<<".x : ";
else
std::cout<<"enter point "<<i/2<<".y : ";
std::cin>>coords[i/2][i%2];
}
NPCTrajectory traj(numOfCoords, speed);
traj.AddCoordinates(coords);
std::cout<<coords[0][0]<<", "<<coords[0][1]<<std::endl;
getch();
double currentCoords[2];
currentCoords[0]=double(coords[0][0]);
currentCoords[1]=double(coords[0][1]);
for(;;)
{
traj.HandleEvents(currentCoords);
std::cout<<"current coordinates : ("<<currentCoords[0]<<", "<<currentCoords[1]<<")"<<std::endl;
std::cout<<"do you wish to continue? ";
getch();
}
}
Trajectories.h 只包含类声明,所以我认为它是无关紧要的。这是我的轨迹.cpp
#include "trajectories.h"
int FPSCap=5;
NPCTrajectory::NPCTrajectory(int npoints, int newSpeed)
{
numOfPoints=npoints;
this->speed=newSpeed;
points = new int * [npoints];
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
state = 0;
maxOffset=speed/FPSCap;
}
void NPCTrajectory::AddCoordinates(int ** coordinates)
{
for(int i=0;i<this->numOfPoints; i++)
{
points[i][0]=coordinates[i][0];
points[i][1]=coordinates[i][1];
}
}
void NPCTrajectory::HandleEvents(double (¤tCoordinates)[2])
{
if(state+1==numOfPoints) return;
if(Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1])<maxOffset) state++;
double ratio = maxOffset/Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1]);
currentCoordinates[0]+=(points[state+1][0]-currentCoordinates[0])*ratio;
currentCoordinates[1]+=(points[state+1][1]-currentCoordinates[1])*ratio;
}
请注意,删除命令traj。添加坐标(坐标)将使问题消失。我是否正确地将数组传递给函数?
问题出在您的构造函数 NPCTrajectory。将 n 点替换为循环变量 i。以下代码:
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
应该是这样的:
for (int i=0; i<npoints; i++)
points[i] = new int[2];
由于这种不正确的分配,当您尝试使用 i=0 访问点 [i][0] 时,您会在 AddT坐标函数中出现错误(分段错误)(假设您在 NPCTrajectory 中给出 npoints>0)。
相关文章:
- pyserial arduino 字节阵列解码问题
- 超级对撞机2D阵列:生成嵌套:包装/尺寸问题
- 阵列火稀疏矩阵问题
- 复制到新阵列时出现动态内存分配问题
- char,const char*阵列问题,用于mqtt client.publish
- 问题将信息复制到指针阵列中
- 问题创建和返回锯齿状阵列(错误std :: bad_array_new_length)
- 顶点阵列与类问题
- 自我创建级阵列[2]正在引起问题
- 气泡排序问题不会更改输入阵列
- C++动态阵列索引和容量问题
- 通过多维阵列迭代问题
- 相同大小的2D和1D阵列之间的内存或执行问题
- 阵列出现问题:/
- 存储到阵列的问题
- 在 2D 图像阵列中裁剪/插入 - 内存分配问题
- 阵列初始化问题
- C++阵列初始化的氧气问题
- 了解 DXGI DirectX 11 桌面复制以获取缓冲区或阵列的问题
- 阵列分配问题