简体   繁体   中英

Dynamic memory allocation initialisation in C++ class

(I'm not posting my code as this is for a project, however I have tried to get help for this issue but have had no luck)

Hi there, I am trying to initialise the size of an array of pointers ( char* ) which is a private member variable of my class class A

I'm using the constructor to set the size by setting an integer variable (also a member variable) which will then be used to create my array of pointers.

I have done this so far:

// Constructor - 'int value' is set to a value
private:
    int value;
    char ** myArray = new char*[value];

So basically I want an array of pointers in which each element can point to a string. I am passing string variables to myArray by using ( char* ) stringVar.c_str();

Although all of this works, I am getting some pretty weird errors when trying to store variables and have even gotten this error:

free (): invalid next size (fast)

It's weird because even when myArray is of size 4, when I try to access, say, the 3rd element, I get the same error as above.

I am very new to C++ and am very intent on solving these issues. I've had to resort to this forum for help and am looking forward to some ideas from you guys :)

if you are new C++ programmer and want work with C++ String list is better work with std::vector<std::string> for complete tutorial of how using vectors see: http://www.cplusplus.com/reference/vector/vector/

but in you question is String list size fixed?or not? if string list is not fixed you must malloc space for array first time in constructor and then realloc array when you want insert a string in your string list for example:

 class A{
   private:
         char** arrayy;
         int arrayysize;
   A(){
    arrayy = (char**)calloc(1,sizeof(char*));
    arrayysize = 1;
   }
   insertToarrayy(char* data){
        strcpy(arrayy[arrayysize-1],data);
        arrayy = (char**)realloc(arrayy,arrayysize+1);
        arrayysize += 1;

   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM