Skip to main content
edited tags
Link
Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126
edited title
Link

Dynamic Dynamicly sized array inside as a class member

Source Link

Dynamic array inside as a class member

I want to create a dynamic sized array of chars as a member in a class. This is being done inside a library that I've created. I have the .h and the .cpp files created. I'm not sure how to declare the array in the .h file. I've tried a few things so far: char* content; char content[]; But these don't seem to work.

Here's what I have in my .h file:

class bufr{
    public:
    //constructor and deconstructor
    bufr(char* _chars, uint8_t _len);
    ~bufr();
    
    //variables
    uint8_t len;
    char content[];
    
};

Here's what I have in my .cpp file (this is the constructor):

bufr::bufr(char* _chars, uint8_t _len){
    char* content = new char[_len];
    content = _chars;
    len = _len;
}

I've also tried replacing the line content = _chars with:

for (int i = 0; i < _len; i++){
    content[i] = _chars[i];
}

But this also doesn't work. When I print the content member to the serial port from within the constructor, or in the main loop it prints nonsense characters, not what I passed it.

Here's my main loop:

void loop(){
    char chars[] = "1234";
    bufr buf(chars, 4);
}

Have I explained myself well enough? Can anyone give me a hand? Much appreciated!

Oh, and yes, I know - in my deconstructor that's not shown, I have delete [] content

I plan on using this class nested inside another class in a few spots and hoping to take advantage of the dynamic mem allocation. I know I can simply declare an array of fixed length, but I wanted to learn the proper way to use new and delete.

Thanks!