[英]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.
我尝试将输入读入struct变量,然后得到垃圾输出,但是当我初始化静态数组时,我输出了正确的变量。
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
You probably want std:: fill()
: 您可能想要
std:: fill()
:
#include <algorithm>
patient *patients = ...;
size_t count = ...;
std::fill(patients, patients + count, DEFAULT_PATIENT_VALUE);
If you are using a non-POD type , loop over your patient array and initialize each cell. 如果您使用的是非POD类型 ,请遍历患者阵列并初始化每个单元格。
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;
}
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) (假设您的结构仅包含POD类型)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.