By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,246 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

Help on memory allocation of dynamic array within a nested structure

P: 2

I'm trying to create and initialise a dynamic array within a nested structure. The structure is defined as followed:
(C++ code)

Expand|Select|Wrap|Line Numbers
  1. typedef unsigned char uchar;
  2. typedef unsigned int uint;
  4. struct Results_list {
  6.      uchar LocX;
  7.      uchar LocY;
  8.      double* ErrRate;
  9. };
  11. struct DE2_Results {
  12.      uint SampleCount;
  13.       uint LocationCnt;
  14.      double* ClkFreq;
  15.      Results_list* TestList;
  16. };
I'm trying to write a function as followed to create/initialise it.
Expand|Select|Wrap|Line Numbers
  1. DE2_Results* InitResultTable(uint LocationCnt,  uint SampleCount)
  2. {
  4. /*
  5. ClkFreq will have [SampleCount] elements
  7. TestList will have [LocationCnt] elements, each is a structure of "Results_list" 
  8. ErrRate will have [SampleCount] elements
  9. */
  11. }

I am new to this and do not know precisely how to correctly allocate memory to this nested structure array. Please help, thx
Jun 11 '07 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 9,197
struct Results_list {

uchar LocX;
uchar LocY;
double* ErrRate;

struct DE2_Results {
uint SampleCount;
uint LocationCnt;
double* ClkFreq;
Results_list* TestList;
There should be no trouble here.
Expand|Select|Wrap|Line Numbers
  1. Results_list arr[100];
  2. Results_list* arr = new Results_list[100];
These arrays are identical except for the stack or heap location. Each element is a Results_list variable ( 2 uchar plus one double*).

Expand|Select|Wrap|Line Numbers
  1. DE2_Results arr[100];
  2. DE2_Results* arr = new DE2_Results[100];
These arrays are identical except for the stack or heap location. Each element is a DE2_Results variable ( 2 uint plus one plus one double* plus one Results_list*).

Your structs just have pointers to your pther structs. The compiler will allocate memory for the pointer. You are responsible for creating something to point at and to put the address of that thing into the pointer.
Jun 11 '07 #2

P: 2
Thanks, I'll try it out.
Jun 12 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.