Michael
Michael

Reputation: 6899

Initialize Array of Structs Using Pointer - C++...?

How can I initialize this struct array using a pointer? I try to read input into the struct variables and I get garbage output, but when I initialize a static array I output the correct variables.

    unsigned int data = numberOfLines();
    patient *q; //struct pointer

    q = new patient[data];

   //What I want to do
   q = new patient[data] = {0,0,0,0,0}; // initialize the array

Upvotes: 0

Views: 1035

Answers (3)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

You probably want std:: fill():

#include <algorithm>

patient *patients = ...;
size_t count = ...;
std::fill(patients, patients + count, DEFAULT_PATIENT_VALUE);

Upvotes: 1

vpiTriumph
vpiTriumph

Reputation: 3166

If you are using a non-POD type, loop over your patient array and initialize each cell.

If you want to get fancy you could gain a little bit of flexibility by creating a function to do this.

patient * createInitializedPatientArray(patient defaultPatient, int length)
{
    patient * temp = new patient[length];
    for(int x = 0; x < length; x++) 
        temp[x] = defaultPatient;
    return temp;
}

Upvotes: 0

karlphillip
karlphillip

Reputation: 93410

Maybe you are looking for an elegant solution to clear the entire array of structures:

memset(q, 0, sizeof(patient) * data);

(assuming your structure contains only POD types)

Upvotes: 0

Related Questions