2012-02-15 2 views
0

배열에 포인터 쌍을 전달하고, 배열 배열을 포함하는 파일을 읽고, 동적으로 배열을 할당하여 포인터를 통해 함수 외부의 배열에 액세스하려고합니다. Visual C++ 2008 Express 컴파일러를 사용하고 있습니다.어떻게 동적 배열을 C++의 메서드 밖으로 전달할 수 있습니까?


#include <GL/gl.h> 
#include <GL/glu.h> 
#include <GL/glut.h> 
#include <fstream> 
#include <stdio.h> 
using namespace std; 
// point object 
class GLintPoint{ 
public: 
    GLint x,y; 
    GLintPoint(){x=0;y=0;} 
    GLintPoint(GLint X,GLint Y){x=X;y=Y;} 
}; 
// pass name of the file followed by points to return 
void readPolyLineFile(char * filename, GLintPoint ** polylines, GLint *polyCount) 
{ 
    fstream inStream; 
    inStream.open(filename, ios::in); 
    if(inStream.fail()) return; 
    // number of arrays, size of each array,, values of each point 
    GLint numpolys, numLines, x, y; 
    inStream >> numpolys; 
    polylines = new GLintPoint*[numpolys]; 
    polyCount = new GLint[numpolys]; 

    for(int j=0;j < numpolys; j++) 
    { 
     inStream >> numLines; 
     polyCount[j] = numLines; 
     polylines[j] = new GLintPoint[numLines]; 

     for(int i=0;i<numLines;i++) 
     { 
      inStream >> x >> y; 
      polylines[j][i].x = x; 
      polylines[j][i].y = y; 
     } 
    } 
    inStream.close(); 
    return; 
} 

폴리 라인은 내가 원하는 데이터 인 점 배열을 보유 할 배열입니다. polyCount는 폴리 라인 내의 각 개별 배열의 크기입니다.

지금까지이 함수를 실행할 때마다 예상대로 실행되지만 포인터를 호출 한 곳의 행으로 돌아 오면 포인터가 null로 설정되고 배열이 아마도 삭제됩니다. 왜 내 함수가 이러한 배열을 삭제하고 반환 할 때 동적 배열을 유지하기 위해이 동작을 어떻게 변경할 수 있습니까? 어떤 도움이라도 대단히 감사하겠습니다.

+0

'boost :: shared_ptr '/'boost :: shared_array '/'std :: shared_ptr '를 사용 해본 적이 있습니까? – moshbear

+6

배열 대신 실제로'std :: vector '또는 중첩 된 동등 물을 사용해야합니다. 그러면 할당 (위험하고 위험 할 수도있는)과 반환 (벡터를 반환하고 MSVC는 RVO를 수행합니다)을 단순화합니다. – ssube

+0

+1 to std :: vector. 모든 포인터를 죽여라. –

답변

0

C++을 사용 중이므로 인수를 참조로 전달하거나 다른 포인터 리디렉션을 추가 할 수 있습니다.

참조로 전달 :

void readPolyLineFile(char * filename, GLintPoint ** &polylines, GLint *&polyCount) 

그런 다음 당신이 "있는 그대로"변수를 사용할 수 있습니다.

다른 솔루션은 더 "순수 C"솔루션이며, 다른 포인터 리디렉션을 추가하는 것입니다

void readPolyLineFile(char * filename, GLintPoint ***polylines, GLint **polyCount) 

는 그런 다음 변수에 할당 할 때 역 참조 포인터를 사용할 필요가 :

*polylines = new GLintPoint*[numpolys]; 
*polyCount = new GLint[numpolys]; 

// ... 

(*polyCount)[j] = numLines; 

// ... etc... 
+0

감사합니다. @ 요아킴! 이것은 저에게 상당히 어려움을주고있었습니다. –

관련 문제