当前位置:网站首页>Void pointer (void*) usage

Void pointer (void*) usage

2022-06-12 13:50:00 qq_ forty-two million seven hundred and seventy-five thousand n

void* Is a special type of pointer , Can be used to store the address of any object .

void *pv =&obj; // obj  It can be any type of object 

1. As a function parameter

#include <stdio.h>

int void_test(void* data)
{
    
    int num = 0;

    num = *(int*)data; 		// (int*) The role of the data Think of it as a int The pointer ( Cast )
    printf("num = %d\n", num);

}

int main()
{
    
    int val;

    val = 123;
    void_test(&val);
    return 0;
}
//  Compile and run the above code , The output is :
// num = 123

2.void Plus one operation of pointer

stay ANSI The following code in is wrong

void * pvoid;
pvoid++; //ANSI: error 
pvoid += 1; //ANSI: error 

GNU Appoint void * The algorithm operation and char * Agreement

void * pvoid;
pvoid++; //GNU: correct 
pvoid += 1; //GNU: correct 

To cater to ANSI standard , And improve the portability of the program , We can write code that does the same thing :

void * pvoid;
(char *)pvoid++; //ANSI: correct ;GNU: correct 
(char *)pvoid += 1; //ANSI: error ;GNU: correct 

GNU and ANSI There are also some differences , Overall speaking ,GNU a ANSI more “ to open up ”, Provides support for more Syntax . But when we're actually designing , Or should we try to cater to ANSI standard .

other

If the argument to a function can be a pointer of any type , Then it should be declared that the parameter is void *
Typical examples are memory operation functions memcpy and memset The function prototypes of are :

void * memcpy(void *dest, const void *src, size_t len);
void * memset ( void * buffer, int c, size_t num );

Reference resources :https://www.cnblogs.com/geekham/p/4225993.html

原网站

版权声明
本文为[qq_ forty-two million seven hundred and seventy-five thousand n]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010515077525.html