编译后可执行文件出错

时间:2014-02-25 03:01:54

标签: c++ windows

你可以帮我解决我的代码中的问题吗?

该程序应该要求用户输入狗的名字,最后打印第三只狗的名字。当我编译并执行程序时,它说“它停止工作”并且Windows询问我是否要关闭程序或做其他事情。

#include<iostream>
#include<cstdlib>
using namespace std;

main()
{
    string perros[10];
    int i;
    for(i=1; i<11; i++)
    {   
        cout<<"Introduce el nombre del perro"<<endl<<i;
        cin>>perros[i];

    }

    cout<<"El nombre del tercer perro es "<<perros[2];
    system("pause");
}

3 个答案:

答案 0 :(得分:1)

数组索引从零开始;所以你的循环应该是

for(i=0; i<10; i++)

你们试图写入10元素阵列的第11个元素,破坏记忆并释放无尽的混乱。

答案 1 :(得分:1)

你应该从0到9开始循环

for(i=0; i<10; i++)

希望这会消除错误...

答案 2 :(得分:0)

您需要从零开始索引,而不是一个索引,因为这是C / C ++数组索引的方式。您将溢出堆栈对象的最大大小。

因此,在原始代码中解决此问题后,您会写出类似的内容:

#include<iostream>
#include<cstdlib>
using namespace std;

main()
{
    string perros[10];
    int i;
    for(i=0; i<10; i++)
    {   
        cout<<"Introduce el nombre del perro"<<endl<<i;
        cin>>perros[i];

    }

    cout<<"El nombre del tercer perro es "<<perros[2];
    system("pause");
}

请注意,您也不要使用for循环,因为它打算使用。您可以将int i;行合并到for循环中。

然而,更智能和C ++的解决方案是使用标准算法,而不是非常低级别的索引,正是为了避免这些问题。

所以,你会写这样的东西:

#include<iostream>
#include<cstdlib>
#include <algorithm>
using namespace std;

void readNextString(string str)
{
    cout<<"Introduce el nombre del perro"<<endl;
    cin >> str;
}

main()
{
    string perros[10];
    for_each(perros, perros + 10, readNextString);
    cout<<"El nombre del tercer perro es "<<perros[2];
    system("pause");
}