0

I am trying to read in names from a file that is given to me. The number of names that are read is based on user input. This compiles fine, but when I run it I get this error:

"0xC0000005: Access violation writing location 0xabababab."

I have done some research and I think it's probably because I am writing over the bounds of the array, but I cannot figure out why this is the case.

Before anyone asks I was told that I have to use string* for my array. I am not to use vectors or array of characters. Thank you.

    int Capacity;
    int numNames = 0; // wasn't in original question, but was in the code
    cin >> Capacity; 

    string name;
    string* arr = new string[Capacity];

    while( !fs.eof() && numRead < Capacity)
    {
         getline( fs , names);
         arr[numRead] = names;  // error thrown here
         arr++;
         numRead++;
    }
2
  • 1
    You're doing arr++ Could also just change your loop to do: std::getline(fs, arr[numRead++]); and get rid of names and everything else.. Don't forget to call delete[] arr when finished with it. Commented Feb 3, 2014 at 1:04
  • also get rid of !fs.eof(), it's the wrong check. instead, terminate the loop when getline fails. Commented Feb 3, 2014 at 1:18

3 Answers 3

1

You can not increment the array starting address (arr++), By doing that you are loosing the control over the array. Array indexing is only valid, if the array reference is pointing to the first element of the array. So remove the arr++ code line, and as David said you must initialize numRead to zero, otherwise some assigned larger random numbers also will cause this error

Sign up to request clarification or add additional context in comments.

Comments

1

You must not increment arr. Remove that line of code. You are using array indexing, arr[numRead], to access the elements of the array.

I also see no evidence that you initialized numRead to 0 before the loop begins.

Comments

0

Use the vector Luke! It would be like: std::vector arr; And then in the loop add the name to the vector like this: arr.push_back(name);

The code you are writing is C not C++ And please stop down voting questions

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.