이중 포인터 예문

Study/C 2014. 8. 27. 15:41

num1와 num2 의 데이터를 스왑하는 소스이다. 문장에서 틀린것을 고치시오.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
 
void SwapIntPtr(int *p1, int *p2)
{
    int * temp= p1;
    p1=p2;
    p2=temp;
}
int main()
{
    int num1=10, num2=20;
    int *ptr1, *ptr2;
    ptr1=&num1;
    ptr2=&num2;
    printf("*ptr1 : %d,  *ptr2 : %d \n",*ptr1, *ptr2);
 
    SwapIntPtr(&ptr1, &ptr2);
    printf("*ptr1 : %d,  *ptr2 : %d \n", *ptr1, *ptr2);
 
    return 0;
}



아래 그림은 틀린 소스에서의 각 주소값들.








수정된 소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
 
void SwapIntPtr(int **p1, int **p2)
{
    int * temp= *p1;
    *p1=*p2;
    *p2=temp;
}
int main()
{
    int num1=10, num2=20;
    int *ptr1, *ptr2;
    ptr1=&num1;
    ptr2=&num2;
    printf("*ptr1 : %d,  *ptr2 : %d \n",*ptr1, *ptr2);
 
    SwapIntPtr(&ptr1, &ptr2);
    printf("*ptr1 : %d,  *ptr2 : %d \n", *ptr1, *ptr2);
    return 0;
}



ptr1, ptr2의 데이터값을 함수로 입력하는 것이라면 이중포인터는 필요없으나 

(틀린소스는 ptr들의 저장된 값만 저장된것)


주소를 변경해야하므로 ptr1과 ptr2의 주소를 받기위해 이중 포인터를 사용한다




마지막으로 스왑에 성공한 이중포인터 소스의 주소값이다. (아래)




'Study > C' 카테고리의 다른 글

탐색 알고리즘  (0) 2014.08.30
함수포인터  (1) 2014.08.27
이중 포인터  (0) 2014.08.27
2차원 배열 (데이터 입력하기)  (0) 2014.08.27
포인터 (3) call by reference  (0) 2014.08.27
Posted by 차희빈

차희빈

달력