2014/05/20

[C/C++] 幾個容易搞混的指標pointer用法整理

1.pointer integer
int i, *pi;
i = 10;
pi = &i;
int *pi; --> 表示pi代表一個記憶體位址,*pi會取出這個記憶體位址所儲存之值
int i; &i --> 表示取出i所在的記憶體位址

2.pointer array
int list[5] = {0, 1, 2, 3, 4};
list代表list[0]所在的記憶體位址,所以透過指標*(list+i)就可以相當於取list[i]之值



3.call by reference
print_call_by_reference(list,5);
print_call_by_reference(&list[0],5);
array透過指標來傳遞,list代表是記憶體位址,相當於list[0]的記憶體位址,也就是&list[0]

4.pointer structure
strptr test, *testptr;
test.data = 1;
test.ptr = &i;
testptr = &test;
宣告struct結構與結構指標,test為strptr結構;testptr為strptr結構指標,差別是test要用test.data取值,而testptr則要用testptr->data取值
附註:(*testptr).ptr與testptr->ptr同樣意思

5.pointer structure & call by reference & call by value
strptr test_call;
test_call.data=100;
test_call.ptr = &(test.data);
print_call_by_reference_struct(&test_call);
print_call_by_value_struct(test_call);
與array不同的是,struct可以透過call by reference和call by value來傳遞參數。

參考程式碼
/* pointer example */
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int data;
    int *ptr;
}strptr;

int main()
{
    // 1.pointer integer: *pi: means pi represent an address
    printf("1.pointer integer\n");
    int i, *pi;
    i = 10;
    pi = &i;
    printf("i: %d, pi: %d, *pi: %d\n", i, pi, *pi);

    // 2.pointer array
    printf("\n2.pointer array\n");
    int list[5] = {0, 1, 2, 3, 4};
    printf("list: %d, list[2]: %d, list+2: %d, *(list+2): %d\n", list, list[2], list+2, *(list+2));


    // 3. call by reference , (list) is as the same as &list[0]
    printf("\n3. call by reference\n");
    printf("list of ");
    print_call_by_reference(list,5);
    printf("&list[0] of ");
    print_call_by_reference(&list[0],5);

    // 4. pointer structure
    printf("\n4. pointer structure\n");
    strptr test, *testptr;
    test.data = 1;
    test.ptr = &i;
    printf("test.data: %d, *(test.ptr): %d\n", test.data, *(test.ptr));
    testptr = &test;
    printf("testptr->data: %d, *(testptr->ptr): %d\n", testptr->data, *(testptr->ptr));

    // 5. pointer structure & call by reference & call by value
    printf("\n5. pointer structure & call by reference & call by value\n");
    strptr test_call;
    test_call.data=100;
    test_call.ptr = &(test.data);
    print_call_by_reference_struct(&test_call);
    print_call_by_value_struct(test_call);

    return 0;
}

int print_call_by_reference(int *ptr, int rows)
{
    int i;
    printf("print_call_by_reference\n");
    for(i=0;i<rows;i++)
        printf(" row[%d]: %d ", i, *ptr);
    printf("\n");
    return 0;
}

int print_call_by_reference_struct(strptr *ptr)
{
    printf("print_call_by_reference_struct\n");
    printf(" ptr->data: %d, *(ptr->ptr): %d\n", ptr->data, *(ptr->ptr));
    return 0;
}

int print_call_by_value_struct(strptr ptr)
{
    printf("print_call_by_value_struct\n");
    printf(" ptr.data: %d, *(ptr.ptr): %d\n", ptr.data, *(ptr.ptr));
    return 0;
}

執行結果

沒有留言:

張貼留言