배열에 포인터 쌍을 전달하고, 배열 배열을 포함하는 파일을 읽고, 동적으로 배열을 할당하여 포인터를 통해 함수 외부의 배열에 액세스하려고합니다. 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로 설정되고 배열이 아마도 삭제됩니다. 왜 내 함수가 이러한 배열을 삭제하고 반환 할 때 동적 배열을 유지하기 위해이 동작을 어떻게 변경할 수 있습니까? 어떤 도움이라도 대단히 감사하겠습니다.
'boost :: shared_ptr'/'boost :: shared_array '/'std :: shared_ptr '를 사용 해본 적이 있습니까? –
moshbear
배열 대신 실제로'std :: vector'또는 중첩 된 동등 물을 사용해야합니다. 그러면 할당 (위험하고 위험 할 수도있는)과 반환 (벡터를 반환하고 MSVC는 RVO를 수행합니다)을 단순화합니다. –
ssube
+1 to std :: vector. 모든 포인터를 죽여라. –