Unhandled exception at 0x00898809 in LAB_3.exe: 0xC0000005: Access violation reading location 0xCCCCCCF4. occurred

-2

When using pointer arrays, I keep getting access violation errors. The code looks right in my eyes, I just might be missing something in terms of initialization. The issue is occuring in the function sort_array.

#include<iostream>
#include<fstream>

using namespace std;

struct Item {
    int productNum;
    string productName;
    double unitPrice;
    int unitSold;
};

void sort_array(Item* [], int);

int main() {
    ifstream salesFile;
    Item* anItem;
    Item* itemList[100];
    int productNum;
    string productName;
    double unitPrice;
    int unitSold;

    salesFile.open("sales.txt");

    //Store elements of the file into a Item object, store the object in the array.
    int count = 0;
    while (salesFile >> productNum) {
        salesFile >> productName >> unitPrice >> unitSold;

        anItem = new Item;
        (*anItem).productNum = productNum;
        (*anItem).productName = productName;
        (*anItem).unitPrice = unitPrice;
        (*anItem).unitSold = unitSold;

        itemList[count] = anItem;

        count++;
    }
    
    //Sort the array of Item objects by total revenue.
    sort_array(itemList, count);

    //Display the top two best sellers.
    cout << (*itemList[count]).productName << (*itemList[count - 1]).productName;

}

//Function for sorting.
void sort_array(Item* arr[], int n) {
    int f;
    int i;
    for (f = n; f > 0; f--) {
        for (i = 0; i < f; i++) {
            if (arr[i]->unitPrice * arr[i]->unitSold > arr[i + 1]->unitPrice * arr[i + 1]->unitSold) {
                swap(arr[i], arr[i + 1]);
            }
        }
    }
}

This is not the first time I've ran into this error, and it seems to be popping up every time I'm trying to assign values to a pointer array.

c++
asked on Stack Overflow Feb 26, 2021 by Gregory Ponder • edited Feb 26, 2021 by Gregory Ponder

1 Answer

0
    itemList[count] = anItem;
    count++;

So you initialize itemList[count] and then increment count. So after this, there is no itemList[count] since count has been incremented.

cout << (*itemList[count]).productName << (*itemList[count - 1]).productName;

Ooops. You just dereferenced itemList[count] which was never initialized.

answered on Stack Overflow Feb 26, 2021 by David Schwartz

User contributions licensed under CC BY-SA 3.0