0

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
3
  • 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. Commented Apr 12, 2012 at 3:15
  • This code looks correct as is - how do you read input into the patient structs? Commented Apr 12, 2012 at 3:17
  • Yes, I know that is correct but how can I initialize that array? Thank you Commented Apr 12, 2012 at 3:17

3 Answers 3

1

You probably want std:: fill():

#include <algorithm>

patient *patients = ...;
size_t count = ...;
std::fill(patients, patients + count, DEFAULT_PATIENT_VALUE);
Sign up to request clarification or add additional context in comments.

1 Comment

I believe you mean #include <algorithm>, not #include <algo>.
0

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)

8 Comments

memset() is not safe for C++ classes. :)
@JonathanGrynspan I thought he said structures.
@Jesse I would love to see what that constructor does for member pointers :D
Structures can have constructors too. Without knowing whether the structure is POD, we cannot be sure memset() is safe.
For built-in types, constructor syntax will give you a zeroed value. i.e. new int gives you a pointer to garbage, new int() gives you a pointer to a 0.
|
0

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;
}

3 Comments

Your not stuck with just a for loop, in the case of the OP you could use memset to initialize the array.
@Roger: Only if struct patient is POD.
Noted @RogerStewart . So really two answers could be combined here. For the OP. Please consult Wikipedia's article on PODs and choose appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.