Home > Backend Development > C++ > Does `sizeof(void)` tell us the size of the void type in C or C ?

Does `sizeof(void)` tell us the size of the void type in C or C ?

Mary-Kate Olsen
Release: 2024-12-03 20:05:27
Original
1033 people have browsed it

Does `sizeof(void)` tell us the size of the void type in C or C  ?

Size of the Elusive void

Question:

Can we determine the size of the void type in C or C ? Consider the following code:

void *p = malloc(sizeof(void));
Copy after login
Extension: If sizeof(void) returns 1 in GCC, will the pointer p increment to 0x2346 after p if p initially held 0x2345?

Answer:

The void type fundamentally lacks size, rendering the expression sizeof(void) meaningless and leading to a compilation error. In C , it is strictly prohibited.

Unexpected Discovery:

Surprisingly, when compiling in GNU C, sizeof(void) yields 1. However, this behavior is limited to GNU C and not observed in C or other implementations.

Implications:

Despite the unexpected return value in GNU C, it's crucial to note that void remains a type without size. Pointers to void, such as p in the example, are genuine pointers and can be incremented like any other pointer. The increment operation in the extension question will behave as expected, with p pointing to the next available memory address.

The above is the detailed content of Does `sizeof(void)` tell us the size of the void type in C or C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template