简体   繁体   中英

C++ Exception thrown: Access violation writing

Exception thrown at 0x008F1D0D in whileLTestStr.exe: 0xC0000005: Access violation writing location 0x00770000.

This error comes up during runtime when trying to put one character from one array, into another array.

The error occurs right after inputting the string, it does not close the program, just "pauses" it.

#include "stdafx.h"
#include <iostream>
#include <cstring>

int main()
{
    using namespace std;

    char test[20];
    char result[20];
    int i = 0;

    cout << "Enter a string without symbolic characters: ";
    cin.get(test, 20);

    for (i; (test[i] != '?' || test[i] != '\0'); i++)
    {
        result[i] = test[i];    //Exception gets thrown here
    }

    if (strcmp(result, test) != 0)
    {
        cout << "Fail.";
    }
    else
    {
        cout << result << endl;
        cout << "Success.";
    }

    return 0;
}

I've marked out where the exception gets thrown with a comment.

This program is just for limiting what the user can enter, purely for testing. But I don't understand why this doesn't work.

There is probably some function to do this for me, but I'm still learning the language, and I'm just interested in trying and testing what I can do with the loops etc.

EDIT

After a suggestion I changed the OR operator for the AND operator, and I no longer get the error. However, I do get some really odd behavior.

PICTURE

test[i] != '?' || test[i] != '\\0' test[i] != '?' || test[i] != '\\0' is always true , so you end up running past the bounds of the array, as i++ increments too far.

Did you want an && instead, in place of the || ?

Finally, you need to insert an explicit NUL-terminator to result , else the output will be undefined. A simple way to do that is to initialise the array to an array of \\0 s using

char result[20] = {};
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    using namespace std;

    string test;

    cout << "Enter a string without symbolic characters: ";
    getline(cin, test);

    if (test.find("?") != string::npos )
    {
        cout << "Fail.";
    }
    else
    {
        cout << test << endl;
        cout << "Success.";
    }
}

That's how you can do it with std::string. Learn C++, not C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM