viod
void字⾯意思是“无类型”,void*
⽆类型指针,⽆类型指针可以指向任何类型的数据。
void定义变量是没有任何意义的,当你定义 void a
时编译器会报错。
void真正用在以下两个方面:
对函数返回值类型的限定
对函数参数类型的限定
程序实例
c
#include <stdio.h>
#include <stdlib.h>
// 1. void修饰函数参数和函数返回
void test01(void) {
printf("hello world");
}
// 2. 不能定义void类型变量
void test02(void) {
// void val; //报错
}
// 3. void* 可以指向任何类型的数据,被称为万能指针
void test03(void) {
int a = 10;
void *p = NULL;
p = &a;
printf("a:%d\n", *(int *)p);
char c = 'a';
p = &c;
printf("c:%c\n", *(char *)p);
}
// 4. void* 常用于数据类型的封装
void test04(void) {
// void * memcpy(void * _Dst, const void * _Src, size_t _Size);
}
int main(void) {
printf("test01 print:\n");
test01();
printf("\n\ntest03 print:\n");
test03();
return 0;
}
程序输出
shell
test01 print:
hello world
test03 print:
a:10
c:a