在C/C中,void表示无类型或空,将该指针描述为类似void *p的定义
对于只包含指针位置而不包含指针的类型,常规指针包含两个属性指针的位置和类型。
其中类型可以判断其长度。
借用网友的总结,我觉得总结得很好。
1.void指针是一个特殊的指针
void *vp
//那是因为没有什么类型
//或者说,该类型无法确定指向对象的长度
2 .可以将任何指针分配给void指针
int *p;
void *vp;
vp=p;
//不需要转换
//变量/只获取对象地址,不获取大小
3 .如果3.void指针指定给其他类型的指针,则进行转换
类型* p=(类型* ) vp;
//获取转换类型,即指针变量/对象大小
4.void指针不能取值
*vp//错误
因为void指针只知道指向变量/对象的起始地址
另一方面,由于不知道变量/对象的大小(以字节为单位),因此无法正确引用
5 .除非转换,否则5.void指针不能参与指针运算
(类型* ) vp;
//VP==VPsizeof(type )。
当然知道void指针,我们需要用void指针做点什么:
对于字符串指针,如果从一个字符串复制到另一个字符串
可以使用strcpy这样的函数,对结构体来说可以直接相等,
但是,在int a[2]这样其他类型的排列的情况下; 怎么复制数据
当然一个要素一个要素的复制当然可以,是不是有点麻烦? 那么我们就这样做
演示,然后结构体也使用了这样的方法。
gaopeng @ bogon :~~/cplusplus $ vites T3.c
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *。
2 File Name: test3.c
3 Author: gaopeng
4 Mail: gaopp_200217@163.com
5 created time : thu 05 may 201611336039336057 am CST
6 * * * * * * * * * * * * * * * * *
7//void*memcpy(void*dest,const void *src,size_t n );
8 //
9 #include
10 #include
11 #包含
12
13 struct mystr
14 {
15 int id;
16 char name[10];
17 };
18
19
是20分主(语音)
21 {
2 inta [2]={ 1,2 };
23 int b[2];
24 int *c;
25 struct mystr st1;
26 struct mystr st2;
27结构Mystr * st3;
28
29
30c=(int* ) memcpy ) ) void * (b,) void * (a,8 );
31printf('%d、%d、%dn”、a[1]、b[1]、c[1];
32
33 st1.id=1;
34strcpy(ST1.name,' test ';
35
36//alsocanyoust2=s t1 tocpystructbutintarraynotwayusememcpyfunction;
37
8ST3=(structmystr* ) memcpy ) ) void * ) st2 ),void * ) st1 ),sizeof ) structmystr ) );
39
40printf('%d、%s、%d、%s、%d、%sn '、st1.id、st1.name、st2.id、st2.name、st3-id、st3-name
41
42 }
按以下方式执行:
go Peng @ bogon :~~/cplusplus $./a.out
2,2,2
1,test,1,test,1,test
可见执行没有问题。 使用memcpy创建了内存的副本,memcpy返回指针并强制将其转换为
相应类型的指针是这里的st3和c,因为实际上该指针只是指向st2和b的位置,而memcpy返回一个
指向目标存储器开始位置的指针
这里重要的是:
c=(int* ) memcpy ) ) void * (b,) void * (a,8 );
ST3=(structmystr* ) memcpy ) ) void * (st2 ),void * (st1 ),sizeof ) structmystr ) );
可见,void指针非常有用,需要了解其本质。
来自“ITPUB博客”链接: http://blog.itpub.net/7728585/view space-2094937 /