Question: Understanding the Undefined Size of "void"
In C programming, the keyword "void" represents an absence of type. This raises the question: what is the size of "void"?
Answer:
The type "void" has no defined size in C. It is not a valid type for objects or pointers, so attempting to use it as such would lead to a compilation error. Specifically, the statement:
void n;
is invalid because it tries to declare a variable of a void type, which is not allowed.
Extension: Allocation and Pointer Arithmetic with "void" Pointers
Although "void" has no size, it can be used as a type for pointers. However, such pointers do not point to any specific type or size of data.
The statement:
void *p = malloc(sizeof(void));
results in a compile-time error because trying to allocate memory for a "void" type is nonsensical. The function malloc requires a valid data type to allocate memory for.
In GCC, the expression sizeof(void) surprisingly evaluates to 1. While this might seem like it assigns a size to "void", it is merely an implementation detail that should not be relied upon.
Additionally, the pointer arithmetic p on a "void" pointer is undefined and should not be used. This is because the type of data pointed to by p is unknown, making it impossible to determine what incrementing the pointer would mean.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3