sizeof的标准规定:
https://en.cppreference.com/w/cpp/language/sizeof
sizeof cannot be used with function types, incomplete types, or bit-field glvalues.
When applied to a reference type, the result is the size of the referenced type.
When applied to a class type, the result is the size of an object of that class plus any additional padding required to place such object in an array.
The result of sizeof
is always nonzero, even if applied to an empty class type.
但是,对于gcc来说:
http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html
6.24 Arithmetic on void
- and Function-Pointers
In GNU C, addition and subtraction operations are supported on pointers to void
and on pointers to functions. This is done by treating the size of a void
or of a function as 1.
A consequence of this is that sizeof
is also allowed on void
and on function types, and returns 1.
The option -Wpointer-arith requests a warning if these extensions are used.
因此,对于void和函数来说,其sizeof为1.
例子:
#include <stdio.h>
int test(int i)
{
i++;
}
int main(void)
{
int tmp_int = 1;
int *int_ptr = &tmp_int;
void *void_ptr = &tmp_int;
printf("func name size is: %u\n", sizeof(test));
printf("void size is: %u\n", sizeof(*void_ptr));
printf("int ptr is [%p]\n", int_ptr);
int_ptr++;
printf("int ptr ++ is [%p]\n", int_ptr);
printf("void ptr is [%p]\n", void_ptr);
void_ptr++;
printf("void ptr ++ is [%p]\n", void_ptr++);
return 0;
}
输出:
func name size is: 1
void size is: 1
int ptr is [0x7fff97dec65c]
int ptr ++ is [0x7fff97dec660]
void ptr is [0x7fff97dec65c]
void ptr ++ is [0x7fff97dec65d]