포인터 배열 질문드려요..

xxxvan의 이미지

 void GetPrime(ULong firstNumber, ULong secondNumber, ULong *(*primeNumber), ULong *count){
    ULong remainder;
    ULong i, j, k = 0;
 
    *count = 0;
 
    i = firstNumber;
    while(i <= secondNumber){
        j = 2;
        remainder = i % j;
        while( j < i && remainder != 0){
            j++;
            remainder = i % j;
 
        }
        if( i == j){
            (*count)++;
        }
        i++;
    }
    if (*count > 0){
        *primeNumber = (ULong(*))calloc(*count, sizeof(ULong));
        i = firstNumber;
        while(i <= secondNumber){
            j = 2;
            remainder = i % j;
            while( j < i && remainder != 0){
                j++;
                remainder = i % j;
 
            }
            if( i == j){
               (*primeNumber)[k] = i;
                k++;
            }
            i++;
        }
    }
} 

여기서 primeNumber가 잘 이해가 가질 않습니다.. 책에서는 main 에게 힙에 할당된 기억공간 주소정보를 전달하기 위해 포인터의 포인터 ULong *(*primeNumber)를 쓴다고 나와있는데요. 조금더 자세한 설명부탁드립니다. 그리고 왜 ULong (*primeNumber) 로 매개변수로 사용하면 안되는지도 설명 부탁드립니다.

shint의 이미지

- primeNumber 는 배열이라고 생각 됩니다.
- 이중배열 사용하는것에는 컴파일러마다 문법이 조금씩은 다른것 같습니다.

- Call By Value. Call By Reference
- 이중배열. 이중포인터

플로우챠트 처럼 만들어볼까? 생각이 들어서.

스크래치로 만들어 봤습니다. 스크립트 보기를 보시면. 소스가 보입니다.
https://scratch.mit.edu/projects/60269834/

만들긴 했는데... UI 로 디버깅 하는 방법은 모르겠네요. ㅇ_ㅇ;;

참고해 보세요. 틀릴 수 도 있습니다.
기능과 원리로 배우는 프로그램 - 데이터 - 2중 포인터
https://drive.google.com/open?id=0B_788O9A9oekYVMtNDdxaUNfeTA&authuser=0

malloc과 calloc에 차이
http://blog.naver.com/chrhdhkd/220247186747

★포인터중에 calloc 함수에대해서.....
http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=66596437&qb=Y2FsbG9j&enc=utf8&section=kin&rank=3&search_sort=0&spq=0

[C++] 변수와 데이터 타입의 사용 - bool, unsigned, long, short | C++ / Language 2012.01.18 주's Ti Laboratory
http://blog.naver.com/twogenesis/130129232290

자바스크립트로도 만들어 봤습니다.

<html>
<body>
 
 
<script type="text/javascript">
//http://egloos.zum.com/1heejin/v/1666952
//https://kldp.org/node/151794#comment-611106
 
 
/*
void GetPrime(ULong firstNumber, ULong secondNumber, ULong *(*primeNumber), ULong *count){
    ULong remainder;
    ULong i, j, k = 0;
 
    *count = 0;
 
    i = firstNumber;
    while(i <= secondNumber){
        j = 2;
        remainder = i % j;
        while( j < i && remainder != 0){
            j++;
            remainder = i % j;
 
        }
        if( i == j){
            (*count)++;
        }
        i++;
    }
    if (*count > 0){
        *primeNumber = (ULong(*))calloc(*count, sizeof(ULong));
        i = firstNumber;
        while(i <= secondNumber){
            j = 2;
            remainder = i % j;
            while( j < i && remainder != 0){
                j++;
                remainder = i % j;
 
            }
            if( i == j){
               (*primeNumber)[k] = i;
                k++;
            }
            i++;
        }
    }
} 
*/
 
 
 
function GetPrime( firstNumber, secondNumber, primeNumber, count)
{
    var remainder;
    var i, j, k = 0;
 
    count = 0;
 
    i = firstNumber;
    while(i <= secondNumber){
        j = 2;
        remainder = i % j;
        while( j < i && remainder != 0){
            j++;
            remainder = i % j;
 
        }
        if( i == j){
            (count)++;
        }
        i++;
    }
    if (count > 0){
        i = firstNumber;
        while(i <= secondNumber){
            j = 2;
            remainder = i % j;
            while( j < i && remainder != 0){
                j++;
                remainder = i % j;
            }
            if( i == j){
                primeNumber.push(i);
                k++;
 
                document.write("<p>" + i + "</p>");
            }
            i++;
        }
    }
}
 
var arPrimeNumber = new Array();
 
GetPrime( 0, 10, arPrimeNumber, 100);
 
delete arPrimeNumber;
arPrimeNumber = null;
 
 
 
</script>
 
</body>
</html>
 
 
출력결과
2
 
3
 
5
 
7

자세한건 C언어 책 참고해 보세요.

이것저것 참고해보세요.
학원. 직업학교
대학교
도서관. 서점
사이버 대학. 디지털 대학. 방송 통신대

댓글 첨부 파일: 
첨부파일 크기
Package icon GetPrime.zip2.52 KB
HTML icon GetPrime.html2.05 KB

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

익명 사용자의 이미지

GetPrime 함수는 firstNumber ~ secondNumber 사이의 소수들을 primeNumber 배열로 리턴해 주고, 소수들이 개수(배열의 크기)도 count에 리턴해 줍니다.
GetPrime 함수를 사용하는 코드를 생각해 보시면 이해가 되실 겁니다. 아래 메인함수..

void GetPrime(ULong firstNumber, ULong secondNumber, ULong *(*primeNumber), ULong *count);
 
int main()
{
    ULong *primeNumber = NULL;
    ULong count = 0;
    int i;
 
    GetPrime(1, 100, &primeNumber, &count);
 
    for(i=0; i < count; i++)
    {
        printf("%d\n", primeNumber[i]);
    }
 
    free(primeNumber);
 
    return 0;
}

primeNumber가 동적할당되어야 하는데, 동적 할당 자체는 GetPrime함수에서 수행되니, 동적할당된 주소값을 얻어오려면 저런식으로 넘겨야죠.
파라미터 선언을 그냥 ULong *primeNumber로 선언하면, 동적할당된 주소값을 얻어오지 못합니다.
(main의 primeNumber는 계속 NULL이고, 메모리 릭이 발생합니다.)

포인터 변수도 그냥 포인터 값을 가지고 있는 보통 변수입니다.
포인터 변수가 가지고 있는 포인터 값을 함수 호출을 통해 수정하려면
call by reference로 넘겨야 하고(count 처럼), 원래 포인터 변수였기 때문에, 파라미터로 넘기는 것은 포인터의 포인터가 되어야 call by reference가 됩니다.

라스코니의 이미지

함수 파라미터에 (int a, int *b, int **c) 가 있다면
이 함수 호출시 아래와 같이

a (값)
b의 어드레스 (값)
(&c)의 어드레스 (값)

들이 스택에 넣어지고 나서 그 다음에 함수가 호출됩니다.
함수가 수행되고 있는 동안에는 이 스택에 넣어진 값들이 참조되는 것입니다.

따라서 어떤 함수에서 일어난 결과를 사용하고 싶을 때는 그 것을 return 값으로 받거나 int *b, int **c 값이 포인터 값으로 넘겨주어야 합니다. 잘 생각해 보시면 calloc() 와 같이 메모리 할당 결과를 부모 함수로 넘겨줄려면 int **c 와 같이 파라미터를 설정해줘야 한다는 것을 아실 수 있을 겁니다. 왜냐하면 할당 결과를 받을 변수는 파라미터로 주기전에 NULL 또는 쓰레기 값을 가지게 되기 때문입니다. 주의를 기울인다면 NULL로 초기화해주는 것이 안전하겠죠.

아래를 참고해 보세요.

int *addr = NULL;
private_memory_allocation(&addr);
....
}

void private_memory_allocation(int **ptr)
{
*ptr = calloc();
}

만약

int *addr = NULL;
private_memory_allocation(addr);
....
}

void private_memory_allocation(int *ptr)
{
ptr = calloc();
}

이렇게 바꾸게 되면 calloc()의 결과가 그냥 스택에만 남겨지게 되기 때문에 부모 함수는 그 값을 가져올 수가 없습니다.
결과적으로 결과를 가져오려면 스택에 넣어진 값이 addr 을 가리키도록 만들어야 합니다. 그래서 addr의 주소인 &addr 을 넘겨주는 것입니다.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.