Void and void * usage

Source: Internet
Author: User

# Include <stdio. h>
# Include <stdlib. h>

Int F ()
{
Return 0;
}
Int main (INT argc, char * argv [])
{
F (10); // if the function is int F (void), an error is returned.
Int * PI;
Void * PV;
Pi = PV;
Pv = PI;
// * Pv = 8; Error
// PV [0] = 4; Error
Int * P = (int *) malloc (100 * sizeof (INT ));
Free (P );
System ("pause ");
Return 0;
}
Under the C CompilerC does not perform parameter check on F (). Therefore, if F (10) is written in the main function, the compiler does not report an error.

Int F (void)

{

Return 0;

}

In this case, F (10) in the main function reports an error because void indicates that the compiler has no parameters.

Note: The C ++ compiler does not have any parameters by default. Whether you write int F () or Int F (void), an error is reported for F (10) in the main function.

The void * Table points to an uncertain object type. Void * can be directly transformed with any pointer, except for function pointers.

For example:

Int * PI;
Void * PV;
Pi = PV;// Note that PI = (int *) PV must be converted in the C ++ compiler;
Pv = PI;

Because void * can be directly transformed with any pointer, except for function pointers,Under the C Compiler, We know that the return type of the malloc function is void *, so the next two sentences are equivalent.

Int * P = (int *) malloc (100 * sizeof (INT ));

Int * P = malloc (100 * sizeof (INT ))

However, void * cannot be used for values or small tables.

// * Pv = 8; Error
// PV [0] = 4; Error

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.