c++ - 在线编译的代码抛出分段错误
问题描述
我在在线编译器上运行此代码:
#include <iostream>
using namespace std;
int main () {
int x_coordinate = 0, y_coordinate = 0;
int numberOfMoves;
cin >> numberOfMoves;
// cout << "i went here" << x_coordinate << numberOfMoves;
string direction[numberOfMoves] = {"right", "up", "left", "down", "right"};
int dir[numberOfMoves] = {0, 1, 2, 3, 0};
for (int i = 1; i <= numberOfMoves; i++) {
// cout << "i went here";
int distance = (i%5)*10;
int currentDirection = dir[i % 5];
switch (currentDirection) {
case 0:
x_coordinate += distance;
break;
case 1:
y_coordinate += distance;
break;
case 2:
x_coordinate -= distance;
break;
case 3:
y_coordinate -= distance;
break;
default:
break;
}
}
cout << x_coordinate << y_coordinate << "\n";
return 0;
}
我得到一个segmentation error
. 有人可以帮我解决这个问题吗?
看完numberOfMoves
代码就停下来执行,我相信。但我不确定。
解决方案
从非法的可变长度数组更改为 C++std::vector
容器非常有可能解决您所有的分段错误问题,我不会详细介绍。
推荐阅读
- php - 日期时间比较在 MySQL 中返回错误结果
- angular - 无法在 catcherror Angular 6 中设置超时
- audio - 使用 UWP 监控实时音频并检测枪声/拍手声
- jmeter - 响应代码:503 响应消息:服务不可用
- sql-server - 操作数数据类型“text”对“max”运算符无效
- vb.net - 如何在 Outlook 加载项打开时启用选择新电子邮件?
- c# - 使用 IE11 在 C# 上使用 IEDriverServer 和 Selenium 时出现内存泄漏
- php - 我提交此表单时出现此错误“HTTP ERROR 500”。谁能告诉我如何解决这个问题?
- android - 项目菜单标题长于 DrawerLayout
- c# - 在 .Net Core 2.0 WebAPI 控制器中获取当前的 http 上下文用户