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
link|improve this question

69% accept rate
There's nothing wrong with what you have shown here, although as soon as you finish the week your class teaching dynamic allocation with new[] and delete[], you should switch to std::vector that someone else has already debugged. – Ben Voigt yesterday
This code looks correct as is - how do you read input into the patient structs? – birryree yesterday
Yes, I know that is correct but how can I initialize that array? Thank you – Michael yesterday
feedback

3 Answers

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)

link|improve this answer
I believe q = new patient[data](); would do the trick. – Jesse yesterday
memset() is not safe for C++ classes. :) – Jonathan Grynspan yesterday
@JonathanGrynspan I thought he said structures. – karlphillip yesterday
@Jesse I would love to see what that constructor does for member pointers :D – karlphillip yesterday
Structures can have constructors too. Without knowing whether the structure is POD, we cannot be sure memset() is safe. – Jonathan Grynspan yesterday
show 4 more comments
feedback

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;
}
link|improve this answer
Your not stuck with just a for loop, in the case of the OP you could use memset to initialize the array. – Roger Stewart yesterday
@Roger: Only if struct patient is POD. – Jonathan Grynspan yesterday
Noted @RogerStewart . So really two answers could be combined here. For the OP. Please consult Wikipedia's article on PODs and choose appropriately. – vpiTriumph yesterday
feedback

You probably want std:: fill():

#include <algorithm>

patient *patients = ...;
size_t count = ...;
std::fill(patients, patients + count, DEFAULT_PATIENT_VALUE);
link|improve this answer
I believe you mean #include <algorithm>, not #include <algo>. – Roger Stewart yesterday
I did, yes, excuse me. – Jonathan Grynspan 19 hours ago
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.