C language void type

1. Function return value

        When a function does not need to return any value, void can be used as the return type.

void hello() 
{
    printf("Hello, World!");
}

2. Function parameters

        When a function does not need to receive any parameters, void can be used as the parameter type.

void swap(int *a, int *b) 
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

3. Pointer type

        A void pointer can point to any type of data.

int x = 10;
void *p = &x;  // ptr 是一个指向整数的泛型指针
*(int*)p = 20;  // 解引用ptr,并将其转换为指向整数的指针
printf("%d\n", x);  // 输出:20

4. Structure members

        In a structure, you can use void pointers as members to store and access any type of data.

typedef struct {
    void *data; // 使用void指针作为成员
    int len; // 存储数据的长度
} Buffer;

5. Array declaration
        

        In the C99 standard, it is possible to use void as the type of the array element to define arrays of unknown or generic types (such as variable-length arrays) in certain circumstances, but this is usually related to memory management rather than regular variable declarations.

void* arr[10];  // 这里声明了一个包含10个void指针元素的数组

Guess you like

Origin blog.csdn.net/W_Fe5/article/details/135333368