Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic memory inside a struct

I'm editing a piece of code, that is part of a big project, that uses "const's" to initialize a bunch of arrays. Because I want to parametrize these const's I have to adapt the code to use "malloc" in order to allocate the memory. Unfortunately there is a problem with structs: I'm not able to allocate dynamic memory in the struct itself. Doing it outside would cause to much modification of the original code.

Here's a small example:

int globalx,globaly;
struct bigStruct{
    struct subStruct{
            double info1;
            double info2;
            bool valid;
    };
    double data;

    //subStruct bar[globalx][globaly];
    subStruct ** bar=(subStruct**)malloc(globalx*sizeof(subStruct*));
    for(int i=0;i<globalx;i++)
            bar[i]=(*subStruct)malloc(globaly*sizeof(subStruct));


};
int main(){
    globalx=2;
    globaly=3;
    bigStruct foo;
    for(int i=0;i<globalx;i++)
            for(int j=0;j<globaly;j++){
                    foo.bar[i][j].info1=i+j;
                    foo.bar[i][j].info2=i*j;
                    foo.bar[i][j].valid=(i==j);
            }

    return 0;
}

Note: in the program code I'm editing globalx and globaly were const's in a specified namespace. Now I removed the "const" so they can act as parameters that are set exactly once.

Summarized: How can I properly allocate memory for the substruct inside the struct? Thank you very much!

Max

like image 756
Maximilien Avatar asked Mar 22 '10 13:03

Maximilien


3 Answers

I suspect you've got little experience with C++. The logical solution is to allocate the memory in the constructor. It would be rather complex to start teaching C++ from that level here.

like image 166
MSalters Avatar answered Oct 17 '22 01:10

MSalters


Is this C or C++ code. The tags say C++ but the code looks just like C. Why are you using malloc instead of new?

To answer your question. Give the struct a constructor to allocate the memory and a destructor to delete it.

Remember, in C++ the only difference between classes and structs is that members are private by default in a class and public by default in a struct.

like image 27
Glen Avatar answered Oct 17 '22 01:10

Glen


Use constructors to do all initialization (including memory allocation), and destructors to free memory. And do not use malloc since you have tagged your question with C++ tag. malloc is only allocates the memory, it will not initialize objects. The following sample shows how it could look in C++:

struct bigStruct{
    struct subStruct{
            double info1;
            double info2;
            bool valid;
    };

    // constructor
    bigStruct( size_t num_of_subs ) : bar( num_of_subs )
    {
    }
    // destructor
    ~bigStruct()
    {
    }        


protected:
    double data;    
    std::vector<subStruct> bar;
};
like image 24
Kirill V. Lyadvinsky Avatar answered Oct 17 '22 01:10

Kirill V. Lyadvinsky