Home > Enterprise >  Allocating an array in a struct in C
Allocating an array in a struct in C

Time:09-18

I am trying to allocate an array of structs within a struct. Here is my code:

struct t_nd {
  double stuff;
};

struct t_nwork {
  struct t_nd *nds;
};

struct t_nwork net;

// need to allocate the nds array to be of size 10

tried this but failed:

t_nd* net.nds = new t_nd[10];

someone said try a vector, so I tried:

vector<t_node> net.nodes(10);

but yet again failed dismally.

CodePudding user response:

someone said try a vector, so I tried:... but failed

You can use vector as shown below. In the shown program, we have a data member called nds of type vector<t_nd>. Also, we have a constructor that has a parameter of type std::size_t.

struct t_nd {
  double stuff;
};
struct t_nwork {
  //data member of type std::vector<t_nd>
  std::vector<t_nd> nds;
  
  //constructor to set size of vector 
  t_nwork(std::size_t psize): nds(psize)
  {
      
  }
};


int main()
{
    //create object of type t_nwork whose nds have size 10
    t_nwork net(10);
}

Working demo

Method 2

Here we don't have any constructor to set the size of the vector.

struct t_nd {
  double stuff;
};

struct t_nwork {
  //data member of type std::vector<t_nd>
  std::vector<t_nd> nds;
  
};

//create object of type t_nwork whose nds have size 10
t_nwork net{std::vector<t_nd>(10)};

Demo

CodePudding user response:

This is the solution:

#include <iostream>

struct t_nd {
    double stuff;
};

struct t_nwork {
    t_nd* nds;
};

int main() {
    t_nwork net;
    net.nds = new t_nd[100];
    // ...
    delete[] net.nds;
}

This is the solution using vector:

#include <iostream>
#include <vector>

struct t_nd {
    double stuff;
};

struct t_nwork {
    std::vector<t_nd> nds;
};

int main() {
    t_nwork net;
    net.nds.resize(10);
    net.nds[1];
}

CodePudding user response:

#include <iostream>
struct xyz {
    int val;
};

struct abc {
    struct xyz *xyzPtr;
};

int main() {
    struct abc myAbc;
    myAbc.xyzPtr = new xyz[10];
    return 0;
}
  • Related