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

何らかの理由で、3 つの「if」行でセグメンテーション フォールトがスローされますが、どこに問題があるのか​​わかりません。

前もって感謝します。

4

1 に答える 1

1

各反復の開始時に更新ingredienteし、null でないことを確認する前に逆参照しています。null の場合、セグメンテーション違反が発生します。ループはおそらく次の行に沿って構成する必要があります

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

変数名に英語が混ざって申し訳ありません。スペイン語は話せません。

または、NextSiblingElement反復を開始したときに最初の要素が得られる場合は、次のforように置き換えることができますwhile

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

重要な点は、ポインターを取得した後、それを逆参照する前に null をチェックすることです。

于 2010-08-14T01:09:34.973 に答える