CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2006
    Posts
    326

    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

  2. #2
    Join Date
    Feb 2006
    Location
    London
    Posts
    238

    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.

  3. #3
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: How to assign a variable length array in a structure?

    Quote Originally Posted by zhshqzyc
    Suppose a structure


    struc data{
    double *aa;
    int b;};
    aa is an array.
    aa is a pointer.
    Quote 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

  4. #4
    Join Date
    Jan 2006
    Posts
    326

    Re: How to assign a variable length array in a structure?

    if aa is a two dimension array,can I follow the same principle?

  5. #5
    Join Date
    Jan 2006
    Location
    croatia
    Posts
    88

    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
  •  





Click Here to Expand Forum to Full Width

Featured