Click to See Complete Forum and Search --> : How to assign a variable length array in a structure?
zhshqzyc
February 20th, 2006, 10:45 AM
Suppose a structure
struc data{
double *aa;
int b;};
aa is an array.
double *abc
struct data *d1;
abc = d1->aa
can I assign abc as the above
DragForce
February 20th, 2006, 10:51 AM
Technically yes, practically any code like this is scary and dangerous.
Use std::vector instead of vector and smartpointers instead of pointers. You could also consider make datamembers of the structure private and define setters/getters.
treuss
February 20th, 2006, 11:45 AM
Suppose a structure
struc data{
double *aa;
int b;};
aa is an array.aa is a pointer.
double *abc
struct data *d1;
abc = d1->aa
can I assign abc as the aboveIn your example d1 points to undefined memory. So doing the assignment will likely cause a coredump. What you are trying is anyways a very dangerous thing to do. Example:
struc data {
double *aa;
int b;
};
data mydata; // create struct on stack
double *abc = mydata.aa; // abc points to same place as aa
mydata.aa = new double[256]; // create the memory for the array. Allocates memory.
double x = abc[0]; // Big problem. abc does not point to the same place as aa any more.Use std::vector instead:struc data {
vector<double> aa;
int b;
};
data mydata; // create struct on stack
vector<double>& abc = mydata.aa; // abc is a reference to mydata.aa
mydata.aa.resize(256); // create the memory for the array.
double x = abc[0]; // No problem
zhshqzyc
February 20th, 2006, 11:53 AM
if aa is a two dimension array,can I follow the same principle?
XZminX
February 20th, 2006, 12:14 PM
yes.
all you have to do is to make a vector of vectors
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.