尝试将字符串添加到数组时,访问冲突写入位置0xCCCCCCCC

时间:2018-02-11 05:10:11

标签: c++ arrays

我要做的是让代码查看数组字,从该数组中随机选择一个字,并将其放在数组测试中。它应该这样做3次,然后打印阵列测试中的内容。

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <time.h>
#include <windows.h>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
int main() {
    int guess;
    string words[] = {"Me", "You", "Everyone", "Mom", "Dad"};
    string test[3];
    for (guess = 1; guess <= 3; guess++) {
        string word = words[rand() % 4];
        test[guess] = word;
    }
    if (guess == 3) {
        cout << words << endl;
    }
    cin.get();
    return 0;
}

然而,当我运行代码时,我收到此错误:

  

在ConsoleApplication10.exe中0x0F2550D9(vcruntime140d.dll)抛出异常:0xC0000005:访问冲突写入位置0xCCCCCCCC。

我在做什么导致此错误,我该如何解决?

2 个答案:

答案 0 :(得分:1)

string test[3];
for (guess = 1; guess <= 3; guess++) {
    string word = words[rand() % 4];
    test[guess] = word;
}

数组索引从0开始,而不是一个。当guess为3时,您正在访问test数组的第4个元素,但该大小仅被声明为3.访问超过数组的长度意味着您可以访问读取 - 只有内存,导致崩溃。

答案 1 :(得分:1)

在C ++和我所知道的几乎所有其他编程语言中,数组使用这种称为0索引的东西。这意味着元素的索引从0开始计数。第一个元素是索引0,第二个是1,依此类推。如果你有一个大小为n的数组,则最后一个元素被索引为n - 1。

在您的代码中,数组test的大小为3。元素具有索引0,1和2.您的循环从1变为3,因此您在循环中最后一次尝试访问数组末尾的元素,从而导致访问冲突。你应该像这样从0到2循环:

for(int i = 0; i < 3; i++)

顺便说一句,您的代码中还有很多其他问题:

你永远不会为rand()设置种子,所以每次运行程序时都会输出相同的内容。

您使用rand() % 4生成随机数,这将为您提供0到3之间的数字,因此忽略了最后一个单词。

最后的if语句完全没有意义,因为你正在检查guess是否等于3,它永远不会是(它必须大于3才能使循环断开),然后你试图输出整个数组words,不起作用。您应该使用循环输出test而不是guess的每个元素。

包含所有更改的代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
    std::srand(std::time(nullptr)); //set the seed for rand() using the current time
    std::string words[5] = {"Me", "You", "Everyone", "Mom", "Dad"}, test[3];
    for(int i = 0; i < 3; i++)
    {
        test[i] = words[std::rand() % 5];
    }
    for(int i = 0; i < 3; i++)
    {
        std::cout << test[i] << " ";
    }
    std::cout << '\n';
}

我建议你来good book

编辑:您可以合并两个循环,甚至不存储猜测的单词:

#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
    std::srand(std::time(nullptr)); //set the seed for rand() using the current time
    std::string words[5] = {"Me", "You", "Everyone", "Mom", "Dad"};
    for(int i = 0; i < 3; i++)
    {
        std::cout << words[std::rand() % 5] << ' ';
    }
    std::cout << '\n';
}