Pointer arithmetic for void pointer in C

前端 未结 8 1106
执念已碎
执念已碎 2020-11-22 01:23

When a pointer to a particular type (say int, char, float, ..) is incremented, its value is increased by the size of that data type. I

8条回答
  •  既然无缘
    2020-11-22 02:05

    The C standard does not allow void pointer arithmetic. However, GNU C is allowed by considering the size of void is 1.

    C11 standard §6.2.5

    Paragraph - 19

    The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

    Following program is working fine in GCC compiler.

    #include
    
    int main()
    {
        int arr[2] = {1, 2};
        void *ptr = &arr;
        ptr = ptr + sizeof(int);
        printf("%d\n", *(int *)ptr);
        return 0;
    }
    

    May be other compilers generate an error.

提交回复
热议问题