[완료] c++에서 dynamic array를 다른 함수내에서 정의하기?

kashmir의 이미지

c++에서 다음과 같은 표현이 가능한지 궁금합니다. 참고로 VC++2005를 사용하고 있습니다.

...
...
int main (int argc, const char *argv[])
{
...
   int totCells;	        // total number of cells
   int* iDim, * jDim;		// numbers of cells in x,y-directions, array of nBlock
   int* boff;
...
   int declareHere(int totCells, int* iDim);
...
...
   declareHere(totCells, iDim);
...
}
 
int declareHere(int totCells, *iDim)
{
...
   iDim = new int [totCells];
...
}

즉 main()에서 dynamic array를 정의하지만, allocate하는 것은 다른 함수내에서 합니다.

익명 사용자의 이미지

int declareHere(int totCells, *iDim)
{
...
iDim = new int [totCells];
...
}

이렇게 사용한 후에 iDim에 해당하는 값(여기서는 배열의 주소)이 유지되지 않습니다.
int** 이면 몰라도 저런 식으로 넘긴 경우에는 값을 전달할 방법이 없죠.
차라리,
int* declareHere( int toCells )
{
...
int* array = new int[totCells];
...
return array;
}
해서 할당받은 주소를 넘겨주면 되겠네요.

ps. 그렇지만 저렇게 메모리를 할당하는 곳과, 해제하는 곳이 서로 다른 곳에 위치하게 되는 코드는 좋지 않은 것 같습니다.
스마트 포인터를 써서 할당한 메모리를 잘 관리한다면 다른 얘기지만요.

kashmir의 이미지

답변 고맙습니다.

메모리를 할당해야 할 변수가 많아서 변수 정의, 메모리 할당, 헤제를 한 함수 내에서 하면 코드가 길어지는 것 같아서 위와 같은 아이디어를 내봤는데, 안되는 것 같군요.

포트란에서는 include란 명령어를 써서 여러 변수를 allocate했는데..

음. 아쉽군요 ㅎㅎ

익명 사용자의 이미지

int main (int argc, const char *argv[])
{
...
   int totCells;	        // total number of cells
   int* iDim, * jDim;		// numbers of cells in x,y-directions, array of nBlock
   int* boff;
...
   int declareHere(int totCells, int* iDim);
...
...
   declareHere(totCells, &iDim); // 변경
...
}
 
int declareHere(int totCells, int **iDim) // 변경
{
...
   *iDim = new int [totCells]; // 변경
...
}

이런식으로 포인터의 주소를 넘기면 가능할 듯 합니다.
익명 사용자의 이미지

쉽게 사세요.

auto_ptr 안찾아 보셨죠?
auto_ptr은 물론 배열에는 직접 못씁니다.

대신에
vector를 쓴다거나
다른 방법으로는
배열 래퍼 클래쓰를 만들면 됩니다.

class auto_array {
int* ptr;
auto_array(const auto_array&) {}
void operator=(const auto_array&) {}
publc:
    explicit auto_array(size_t sz) : ptr(new int[sz]) {}
    ~auto_array() { delete [] ptr; }
 
    operator int*() { return ptr; }
};

배열 크기가 그다지 크지 않다면
비록 vc는 가변 배열을 지원하지 않지만
alloca는 쓸 수 있습니다.

kashmir의 이미지

답변해주신분들 고맙습니다.

c/c++와 포트란을 이번 2월부터 사용하기 시작했는데 포트란은 매트랩과 비슷한점이 많아서 익숙해지기가 쉬운반면, c/c++는 특히 이 포인터 때문에 알듯하면서도 어렵네요.

결국은 따로 input 파일을 만들어서 그것을 읽어드리고 메인 함수에서 allocate하는 형태로 규현하기로 했습니다. 가장 쉬운 방법인 것 같네요.

vector는 dynamic array보다 더 자연스러운 방법인 것 같아서 쓰고 싶으나 아직 시간이 없어서 쓸 기회가 없네요. 또 클래스가 저에게는 새로운 개념이라서 익숙하지도 않고요.

그래도 재밌습니다 :)

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.