似乎有很多人有分段故障问题,但我似乎找不到任何与我的程序相关的内容,如果有一个线程我很抱歉,我看了很多但是不能找到它。
到目前为止几乎所有事情:
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <time.h>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int maxLandMass = SCREEN_WIDTH * SCREEN_HEIGHT;
const int landPercentage = 30;
const int maxHeight = 200;
const int numAnts = 10;
int main(int argc, char **argv)
{
int currentLandMass = 0;
int ants[numAnts][3]={{0}}; //x,y,pDir (0123,NESW)
std::string rules[numAnts]={0};
std::string rule;
int states = 2;
std::cout << "Which rule would you like to use? ";
std::cin >> rule;
if(rule == "")
{
rule = "RL";
}
else if(rule == "RND" || rule == "rnd")
{
std::cout << "How many states? ";
std::cin >> states;
}
srand(time(NULL));
for(int i = 0;i < numAnts;i++)
{
ants[i][0] = rand() % SCREEN_WIDTH;
ants[i][1] = rand() % SCREEN_HEIGHT;
ants[i][2] = rand() % 4;
if(rule != "RND" && rule != "rnd")
{
rules[i] = rule;
}
else
{
std::string tempRule;
for(int s = 0; s < states; s++)
{
int r = rand() % 2;
if(r == 0){ tempRule += "L"; }
if(r == 1){ tempRule += "R"; }
}
rules[i] = tempRule;
}
std::cout << rules[i] << "\n";
}
SDL_Window* window = NULL;
SDL_Surface* surface = NULL;
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
}
else
{
window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if( window == NULL )
{
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
}
else
{
surface = SDL_GetWindowSurface(window);
SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0x00, 0x00, 0x00));
SDL_UpdateWindowSurface(window);
}
}
//Uint16 *pixels = (Uint16 *) surface->pixels;
/////////////////////////////
int grid[SCREEN_HEIGHT][SCREEN_WIDTH]={{0}};
int heights[SCREEN_HEIGHT][SCREEN_WIDTH]={{0}};
int prevState = 0;
for(int a = 0; a < numAnts; a++)
{
//TODO add stuff here
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
当它运行时,应该从控制台窗口开始,从用户那里获得一些输入,然后切换到SDL窗口并执行其操作,但控制台窗口告诉我: 在抛出'std :: logic_error'的实例后终止调用 what():basic_string :: _ S_construct null无效
我感觉它与我如何初始化(或至少尝试过)数组有关。
我最后添加的部分是我在//////行下面的位。
让我知道如果你需要更多的信息,不适,只要我能得到它,我为我的项目目前的状态道歉,其混乱是推动我有点疯了太多,但(直到我把它弄坏了),它的工作: p
答案 0 :(得分:4)
您正在使用零初始化字符串数组。这是一个无效的初始化。
有趣的是,如果你选择了任何其他数字,你会得到一个更清晰的错误信息,告诉你你正在从int转换为const char *(这是一个c风格的字符串,最近的有效输入类型std :: string有一个构造函数)。 不幸的是,零初始化让你的编译器感到困惑,认为你实际上正在分配一个它可以转换的指针,但幸运的是它检查并发现指针是NULL,因此用你看到的错误信息解决:{ {1}}。
我拿了你的代码并删除了所有的SDL部分,它编译并重现了错误。
然后我替换了basic_string::_S_construct null not valid
带
std::string rules[numAnts]={0};
使用默认构造函数为所有元素创建空字符串,现在它似乎可以工作。