c++arraysstringdynamic-allocation

Dynamically allocated string array, then change it's value?


I'm trying to create a string array and use a pointer to modify it. I'm not sure how to declare the pointer since strings can vary in length, and I think this is what causes the error.

My code looks something like this:

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

string *users = NULL;
int seatNum = NULL;
cin >> seatNum;
users = new string[seatNum];
string name;
cin >> name;
users[seatNum] = name;

It throws me an Write Access Violation when I try to change its value. From what I've read it's because strings are compiled as read-only, so my question is how would I/what would I do to change it? Easy-to-understand explanations would be preferable.


Solution

  • You're accessing memory beyond the range of the allocated array

    users = new string[seatNum];
    users[seatNum] = name;
    

    The first element is [0]. The last is [seatNum-1]