Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as a C++ class member variable

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.

like image 923
FourOfAKind Avatar asked Dec 31 '11 20:12

FourOfAKind


2 Answers

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 *j which is only a pointer to a random memory address. Very, very, very bad.

like image 162
Tom van der Woerdt Avatar answered Oct 17 '22 00:10

Tom van der Woerdt


int j[];

Is not what you think it is. This actually defines a pointer: int* j;, which is left uninitialized, and from which you're reading in the uninitialized state, which is undefined behaviour, aka wrong.

Just use a std::vector.

like image 3
Xeo Avatar answered Oct 17 '22 00:10

Xeo