Search code examples
c++arraysstringswap

Unhandled exception thrown: write access violation: Printing out array elements


I have a function, which prints out an array of strings. The second function is supposed to print the reversed list but for some reason a new tab called xmemory pops up and I get the message: "Unhandled exception thrown: write access violation. this->_Myproxy was 0xCCCCCCCC." After hours of searching for this online, I finally decided to see if someone here could help me.

Here is my code:

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

void display(string array[5]);
void displayReverse(string array[5]);

int main()
{
    string fruit[5] = {"Apple", "Banana", "Orange", "Kiwi", "Cherry"};
    display(fruit);
    displayReverse(fruit);
    return 0;
}

void display(string array[5])
{
    for (int i = 0; i < 5; ++i)
    {
        cout << array[i] << endl;
    }
}

void displayReverse(string array[5])
{
    swap(array[1], array[5]);
    swap(array[2], array[4]);
    swap(array[4], array[5]);

    cout << array[1] << endl << array[2] << endl << array[3] << endl << array[4] << endl << array[5] << endl;
}

Solution

  • Array index start from 0. It won't start from 1. So if you have array with 5 elements, you can access the first element by array[0]. array[1] represents second element. Your displayReverse() is trying to access 6th element in the array which doesn't exist.

    Below is the code with some modifications.

    #include <iostream>
    #include <string>
    using namespace std;
    
    void display(string array[], int size);
    void displayReverse(string array[]);
    
    int main()
    {
        string fruit[5] = {"Apple", "Banana", "Orange", "Kiwi", "Cherry"};
        display(fruit, 5);
        displayReverse(fruit);
        return 0;
    }
    
    void display(string array[], int size)
    {
        for (int i = 0; i < size; ++i)
        {
            cout << array[i] << endl;
        }
    }
    
    void displayReverse(string array[])
    {
        swap(array[0], array[4]);
        //swap(array[2], array[3]);
        swap(array[1], array[3]);
    
        cout << array[0] << endl << array[1] << endl << array[2] << endl << array[3] << endl << array[4] << endl;
    }