Pointer arithmetic for void pointer in C

2018-12-31 05:50发布

When a pointer to a particular type (say int, char, float, ..) is incremented, its value is increased by the size of that data type. If a void pointer which points to data of size x is incremented, how does it get to point x bytes ahead? How does the compiler know to add x to value of the pointer?

8条回答
伤终究还是伤i
2楼-- · 2018-12-31 06:20

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 working fine in GCC compiler.

#include<stdio.h>

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.

查看更多
栀子花@的思念
3楼-- · 2018-12-31 06:26

Pointer arithmetic is not allowed on void* pointers.

查看更多
登录 后发表回答