Question

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.

Was it helpful?

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]

OTHER TIPS

You have created an array of seatNum elements. Array element indexing starts at 0 therefore the range of valid indexes is [0, seatNum - 1]. By accessing users[seatNum] = ... you are effectively going past the last valid element of the array. This invokes UB (undefined behavior).


I see you have already made the right choice of using std::string instead of C-style strings. Why not make the same choice over arrays?

#include <string>
#include <array> 
#include <iostream>

int main(int, char*[]) {
    int seatNum = 0;
    std::cin >> seatNum;
    std::vector<std::string> users(seatNum);
    std::cin >> users[0];
    return 0;
}

Try to avoid pointers and C-style arrays, especially dynamic ones.

A few things:

  1. int seatNum will be allocated on the stack and will never be NULL. You should set it to 0.

  2. You are setting users[seatNum] which is out of bounds causing your program to crash. You can only use indices from 0 to seatNum-1.

Updated: Chris is correct. I looked into it and strings are indeed mutable in C++.

firstly you cannot set null value to int type data

int seatNum = NULL; // wrong 
int seatNum = 0;  // right

secondly string bounds from 0 to seatnum -1

users[seatNum-1] = name; // right
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top