|
-
February 20th, 2006, 11:45 AM
#1
How to assign a variable length array in a structure?
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
-
February 20th, 2006, 11:51 AM
#2
Re: How to assign a variable length array in a structure?
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.
-
February 20th, 2006, 12:45 PM
#3
Re: How to assign a variable length array in a structure?
 Originally Posted by zhshqzyc
Suppose a structure
struc data{
double *aa;
int b;};
aa is an array.
aa is a pointer.
 Originally Posted by zhshqzyc
double *abc
struct data *d1;
abc = d1->aa
can I assign abc as the above
In 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:
Code:
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:
Code:
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
-
February 20th, 2006, 12:53 PM
#4
Re: How to assign a variable length array in a structure?
if aa is a two dimension array,can I follow the same principle?
-
February 20th, 2006, 01:14 PM
#5
Re: How to assign a variable length array in a structure?
yes.
all you have to do is to make a vector of vectors
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|