Can I use array as a member variable of a class in c++ in the following way? or Should I declare it as a pointer? The following code works fine. Is it correct way of doing it? (I made it public just for simplicity). I’m also not sure whether I’m using the map correctly or not.
#include <iostream>
#include <map>
#include <string.h>
using namespace std;
class SimpleMap{
public:
map<string,int> m;
int i;
int j[];
SimpleMap(int ii);
};
SimpleMap::SimpleMap(int ii){
i = ii;
}
int main(){
SimpleMap mm(5);
mm.m["one"] = 1;
cout<<"hi hru";
cout<<mm.m["one"];
mm.j[0] = 11;
cout << mm.j[0];
}
EDIT: I’ve add map member variable.
Actually, you already have a pointer. But it’s uninitialized.
Setting
j[0]will work in some cases, sure, but you’re writing to unallocated memory, or worse, memory used by another object. Basically you’re creating a massive hole in your application.Consider using a
std::vector, which simply does all the allocating/deallocating for you. If that’s not an option, at least initialize the array and don’t go further than you allocated.j[]is simply*jwhich is only a pointer to a random memory address. Very, very, very bad.