我正在尝试读取XML中的元素并将其存储在 struct,需要将此数组的指针传递给其他函数。 但是我在gnu中编译时出现问题,错误消息:error:无法 将'myRec'转换为uint32_t {aka unsigned int}'作为回报 返回* recs;
Please help.
试图在不使用malloc的情况下设置myRec recs [count],并得到无效指针的错误
struct myRec
{
std::string one;
std::string two;
std::string three;
std::string four;
std::string five;
std::string six;
};
uint32_t count = 0;
XMLDocument doc;
doc.LoadFile(pFilename);
XMLElement* parent = doc.FirstChildElement("a");
XMLElement* child = parent->FirstChildElement("b");
XMLElement* e = child->FirstChildElement("c");
for (e = child->FirstChildElement("c"); e; e = e->NextSiblingElement("c"))
{
count++;
}
std::cout << "\n""Count = " << count << std::endl;
recs = (myRec *)malloc(6 *count * sizeof(myRec));
XMLElement *row = child->FirstChildElement();
if (count > 0)
{
--count;
count = (count < 0) ? 0 : count;
for (uint32_t i = 0; i <= count; i++)
{
while (row != NULL)
{
std::string six;
six = row->Attribute("ID");
recs[i].six = six;
XMLElement *col = row->FirstChildElement();
while (col != NULL)
{
std::string sKey;
std::string sVal;
char *sTemp1 = (char *)col->Value();
if (sTemp1 != NULL) {
sKey = static_cast<std::string>(sTemp1);
}
else {
sKey = "";
}
char *sTemp2 = (char *)col->GetText();
if (sTemp2 != NULL) {
sVal = static_cast<std::string>(sTemp2);
}
else {
sVal = "";
}
if (sKey == "one") {
recs[i].one = sVal;
}
if (sKey == "two") {
recs[i].two = sVal;
}
if (sKey == "three") {
recs[i].three = sVal;
}
if (sKey == "four") {
recs[i].four = sVal;
}
if (sKey == "five") {
recs[i].five = sVal;
}
col = col->NextSiblingElement();
}// end while col
std::cout << "\n""one = " << recs[i].one << "\n"" two= " << recs[i].two << "\n""three = " << recs[i].three << "\n""four = " << recs[i].four << "\n""five = " << recs[i].five << "\n""six = " << recs[i].six << std::endl;
row = row->NextSiblingElement();
}// end while row
}
}
else
{
std::cout << "Failed to find value, please check XML! \n" << std::endl;
}
return *recs;
期望返回指向数组的指针
I declared it as
std::string getxmlcontent(const char* pFilename);
myRec*recs= NULL;
function:
std::string readxml::getxmlcontent(const char* pFilename)
{
}
not sure if it is the right way as I am quite new to c++
答案 0 :(得分:1)
您犯了一些错误,您可能应该得到good C++ book并进行一些学习
在C ++中,使用new
recs = new myRec[6*count];
代替
recs = (myRec *)malloc(6 *count * sizeof(myRec));
C ++程序中malloc
的问题在于它不会调用构造函数,因此结构中包含的所有字符串均无效,并且(很可能)您的程序在运行时会崩溃。
我不清楚您为什么需要6*count
,这似乎是因为您的结构中有六个字符串。如果是这样的话,那就太让人困惑了,真的只需要
recs = new myRec[count];
您将获得6*count
字符串,因为这是您声明结构的方式。
sKey = sTemp1;
代替
sKey = static_cast<std::string>(sTemp1);
不需要强制转换,将char*
分配给std::string
是完全合法的。
最后,如果您想返回一个指针,则只需返回指针
return recs;
不是
return *recs;
但是,您尚未在发布的代码中包含函数签名。我怀疑还有另一个错误,但是除非您发布如何声明此函数,否则我无法告诉您。