0

我正在尝试使用 Tinyxml 递归读取 Xml 文件,但是当我尝试访问数据时,我得到一个“分段错误”。这是代码:

int id=0, categoria=0;
const char* nombre;
do{  
    ingrediente = ingrediente->NextSiblingElement("Ingrediente");   
    contador++;  
    if(ingrediente->Attribute("id")!=NULL)
        id = atoi( ingrediente->Attribute("id") );  
    if(ingrediente->Attribute("categoria")!=NULL)
        categoria = atoi ( ingrediente->Attribute("categoria") );  
    if(ingrediente!=NULL)
        nombre = ( ( ingrediente->FirstChild() )->ToText() )->Value();  
}while(ingrediente);    

出于某种原因,三个“if”行向我抛出了分段错误,但我不知道问题出在哪里。

提前致谢。

4

1 回答 1

1

您在每次迭代开始时进行更新ingrediente,然后在检查它是否不为空之前取消引用它。如果它为空,这将给出分段错误。循环可能应该按照以下方式构建

for (ingrediente = first_ingrediente; 
     ingrediente; 
     ingrediente = ingrediente->NextSiblingElement("Ingrediente"))
    contador++;  
    if(ingrediente->Attribute("id"))
        id = atoi( ingrediente->Attribute("id") );  
    if(ingrediente->Attribute("categoria"))
        categoria = atoi ( ingrediente->Attribute("categoria") );  
    nombre = ingrediente->FirstChild()->ToText()->Value();  
}

Sorry for mixing some English into the variable names; I don't speak Spanish.

Or, if NextSiblingElement gives you the first element when you start iterating, the for can be replaced with while:

while ((ingrediente = ingrediente->NextSiblingElement("Ingrediente")))

The important point is to check for null after getting the pointer, and before dereferencing it.

于 2010-08-14T01:09:34.973 回答