FourOfAKind
FourOfAKind

Reputation: 2418

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.

Upvotes: 6

Views: 14921

Answers (4)

Flamefire
Flamefire

Reputation: 5807

As I found that on google I wanted to clear up a confusion here in the answers: Using T name[] as the last member of a struct is called a "flexible array member" and defined as an extension to C by e.g. GCC and Clang. Example use:

struct Array{
  int len;
  float ar[];
};
// Create
Array* foo = malloc(sizeof(Array) + 100 * sizeof(float));
foo.len = 100;
// Use
for(int i=0; i<foo.len; i++) foo.ar[i] = i * M_PI;

The special member is not actually a member but some compiler magic and similar to struct Array{ int len; float ar[100]; }; but you can choose the size at runtime.

However in C++ this is much harder to use as you need to take object lifetime into consideration. So do NOT use this as-is in C++.

In the case of the OP: You probably wanted a real pointer there and need an allocation for the array pointed to. Obviously a std::vector solves most of the trouble as already pointed out.

Upvotes: 0

swe
swe

Reputation: 151

No,I think int j[]; is used when you initialize the array on it's declaration.You should provide an upper bound to the array.I think this would be correct int j[]={3,2,1}; .

Upvotes: 0

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

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.

Upvotes: 7

Xeo
Xeo

Reputation: 131789

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.

Upvotes: 3

Related Questions