Dynamic memory inside a struct
Posted
by Maximilien
on Stack Overflow
See other posts from Stack Overflow
or by Maximilien
Published on 2010-03-22T13:33:13Z
Indexed on
2010/03/22
13:41 UTC
Read the original article
Hit count: 330
Hello,
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
© Stack Overflow or respective owner