Monday, 16 April 2012

Pointer variable


Usually, pointer variables are with type difinition like char *int *long *, and like that. So when you want to  do some operations, compiler will use sizeof(type) as the unit. For example:


#include "stdio.h"

main()
{
    int a[3]={4, 5, 6};
    int *point1;
    point1=a;
    point1=point1+1;
    printf("%d\n", *point1);
    getchar();
}

Result: 5

However, we can use void * to define a point variable without type. But this variable cannot be operated because of the uncertain length of this variable. So before operation, you have to cast the variable to a specific type to do the operations. For example:


#include "stdio.h"

main()
{
    int a[3]={4, 5, 6};
    void *point2;

    point2=a;

    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);
    point2=(char *)point2+1;
    printf("%d\n", *(int *)point2);

    getchar();
}
Result:
1280  --- 00000101  00000000
5
1536  --- 00000110  00000000
6



Reference:
[1] C语言深度解剖读书笔记之----C语言基础测试题, http://blog.csdn.net/feitianxuxue/article/details/7334929

No comments:

Post a Comment

Difference between "docker stop" and "docker kill"

 To stop a running container, you can use either "docker stop" or "docker kill" command to do so. Although it seems doin...