2014-11-20 7 views
0

두 개의 큰 XML 파일을 비교하고 변경된 제품 (노드)의 식별자와 변경 사항을 포함하는 파일을 만들기 위해 C++로 프로그램을 작성했습니다. 이렇게하려면 pugixml을 사용하고 있습니다.const char *를 non const char * 캐스팅 *

저는 현재 PHP 개발자로 일하고 있으며, C++을 사용해 오랫동안 사용 해왔다. 그래서 나는 사소한 것을 간과하고 있다고 생각하지만, 온라인으로 검색 한 후에도 여전히 내 솔루션을 찾지 못했습니다. 문제는 다음과 같습니다.

요소의 태그 사이에 값을 제공하는 child_value 함수는 const char *를 반환합니다. 내가하려는 것은 배열의 모든 값을 넣고 다른 모든 제품의 값과 비교하는 것입니다 (유사한 배열에 있음).

다음 제품으로 갈 때 문제가 발생하며 배열의 값을 덮어 쓸 필요가 있습니다.이 값은 내가 얻고있는 분할 오류의 근원이라고 생각합니다. 그래서 내 질문은 :

나는 그 const char *를 비교할 필요가있다. 그러나 다음 비교를 할 수 있도록 값을 덮어 써야한다. 무엇을하는 것이 가장 좋은 방법인가? strcpy, const_cast (아래의 예제 코드에서와 같은) 및 다른 제안로드했지만 모두 동일한 분할 오류 발생하는 것 같습니다.

컴파일되지만 첫 번째 값을 덮어 쓰려고하면 두 번째 반복에서 충돌이 발생합니다.

for (xml_node groupCurrent = groupsCurrent.child("group");groupCurrent;groupCurrent = groupCurrent.next_sibling("group")){ 

    xml_node productsCurrent = groupCurrent.child("products"); 
    size_t nrProductsInGroupCurrent = std::distance(productsCurrent.children().begin(), productsCurrent.children().end()); 
    nrProductsTotalCurrent = nrProductsTotalCurrent + nrProductsInGroupCurrent; 

    for (xml_node productCurrent = productsCurrent.child("product");productCurrent;productCurrent = productCurrent.next_sibling("product")){ 

     int numberAttributesC=0; 
     char * childrenCurrent[32]; 

     for (xml_node attributeCurrent = productCurrent.first_child();attributeCurrent ;attributeCurrent= attributeCurrent.next_sibling()){ 
      char * nonConstValue = const_cast<char *> (attributeCurrent.child_value()); 
      childrenCurrent[numberAttributesC]=nonConstValue; 
      numberAttributesC++; 
     } 

     /*for(int i = 0;i<numberAttributesC;i++){ 
      std::cout<<childrenCurrent[i]; 
     }*/ 
     //xml_node groupsNew = docNew.child("product_database"); 

    } 
} 

어떤 도움, 제안 또는 의견도 크게 환영합니다. 그 동안 해결책을 찾으면 여기에 게시 할 것입니다.

감사합니다, 안티

PS : 우분투 버전의 gcc 4.8.2

+0

'char * childrenCurrent [32];'? 나는 '벡터 '와 함께 갈 것이다. 어쨌든 pugixml 구현을 모르지만 각 반복'attributeCurrent'가 소멸 된 후에'child_value()'로 얻은 값에 대한 포인터가 여전히 유효한지 알 수 없습니다 (각 노드의 사본을 얻었습니까? 내부 구현에 대한 참조 사본?). '벡터 '을 사용하면 그 값의 _safe_ 복사본을 갖게됩니다. 실제 코드를 유지하려면'strcpy' 대신'strdup'을 사용해야합니다. –

+0

'segmentation error '는'for' 루프가'childrenCurrent [numberAttributesC]'가 허용하는 것보다 더 많은 횟수를 실행한다는 것을 나타냅니다. 'numberAttributesC'가'childrenCurrent - 1의 최대 크기 '를 절대로 초과하지 않는지 확인하십시오. –

답변

0

를 사용하여 그냥 vectorand string

std::vector<std::string> childrenCurrent; 

for (xml_node attributeCurrent = productCurrent.first_child();attributeCurrent ;attributeCurrent= attributeCurrent.next_sibling()) 
{  
    std::string value = attributeCurrent.child_value(); 
    childrenCurrent.push_back(value);  
} 

사용 주 : 나는 child_valueconst char*을 반환 있으리라 믿고있어

string은 값을 사용하여 메모리 문제를 제거하고 vector을 사용하면 잠재적 속성 수를 관리하는 것에 대해 걱정할 필요가 없습니다.

+0

귀하의 빠른 응답을 주셔서 감사합니다, 나는 그것을 밖으로 시도하고 어떻게 작동하는지 알려 드리겠습니다 :) – AntiFTW

+1

그것은 좋은 작품, 그래서 간단하고 우아한 :) 어제부터 이것에 두통이 다시 고마워. – AntiFTW

관련 문제