kakush
kakush

Reputation: 3484

Creating a char array, whose size is given by parameter - C++

I have a class with a static char array. The size of the array is given to me in argv.

I want to do somthing like this:

class ABC {

public:
  static char *buffer;
  ABC(int size) {
    ABC::buffer = new char[size];
  }

}

// in other file:

ABC tempVar(atoi(argv[1]));

but this doesn't seem to work. I get errors like:

Error 2 error LNK2001: unresolved external symbol "public: static char * ABC::buffer" (?buffer@ABC@@2PADA) gpslib.lib

How can I fix this?

Upvotes: 0

Views: 375

Answers (1)

hmjd
hmjd

Reputation: 121971

You need to define the static buffer exactly once, it has only been declared. Add the following to exactly one .cpp file:

char* ABC::buffer;

Note that everytime an instance of ABC is created, the previously allocated buffer will be lost (a memory leak) which is not what you want.

A more robust solution would have buffer as an instance (non-static) member. An even more robust solution would use std::string instead of a char* and have dynamic memory allocation managed for you.

Upvotes: 5

Related Questions