about "void" and "void *"

/* void.c by vinco at 2011-09-09
*   i386-Red Hat-gcc-4.1.2 
*   http://blog.csdn.net/xuyunzhang/
*   
*/

#include<stdio.h>
#include<string.h>
typedef struct stu
{
	int age;
	char name[32];
	
} STU;

int main()
{
	float *pFt;
	int *pInt;
	void *pVd;
	void *pVd1 = pVd;
	
	STU stu = {24, "vinco" };
	STU *pStu = &stu;
	STU *pStu1 = NULL;
	//void data; //1. "error: variable or field data declared void"
	
	//pFt = pInt;// 2. "warning: assignment from incompatible pointer type"
	pFt = (float *)pInt;

	pVd1 ++; // equivalent to (char* )pVd1 ++;
	printf("sizeof(void *) = %d, ( pVd1 - pVd)/sizeof(char) = %d\n", sizeof(void *), ( pVd1 - pVd)/sizeof(char) );
	pVd1 += 1;
	(char* )pVd1 ++;
	//(char* )pVd1 += 1; //"error: invalid lvalue in assignment"
	
	pVd = pInt;
	pInt = pVd; // all right !!!, somebody said it's not !
	pInt = (int *)pVd;

	pVd = pStu;
	pStu1 = pVd;//equivalent to "pStu1 = (STU *)pVd;" all right !!! somebody said it's not !

	printf("pStu->age = %d, pStu->name = %s \n", pStu->age, pStu->name );
	printf("pStu1->age = %d, pStu1->name = %s \n", pStu1->age, pStu1->name );
	// 3. printf("pVd->age = %d, pVd->name = %s \n", pVd->age, pVd->name );
	
	
}

make  an run it

[vinco@IPPBX-Server ctest]$ make void
cc     void.c   -o void
[vinco@IPPBX-Server ctest]$ ./void
sizeof(void *) = 4, ( pVd1 - pVd)/sizeof(char) = 1
pStu->age = 24, pStu->name = vinco 
pStu1->age = 24, pStu1->name = vinco 



analysis:

 void /void *
 I. to define the return type of a function ;
 eg:
     void func();
     void* func();
 II. to define the formal parameter of a function ;
 eg:
    int func(void );
    int func(void * p);
------------------------------------------

1. can not define "void" type data
   "void data;"
   ("error: variable or field data declared void") ;
  
2. be careful when assignment a point of type one with another type;
    float *pFt;
    int *pInt;
    pFt = pInt;
   
"warning: assignment from incompatible pointer type" ;
 
3.
   pVd = pStu;
   printf("pVd->age = %d, pVd->name = %s \n", pVd->age, pVd->name );
   "error: request for member age/name in something is not a structure or union" ;

   code modified as below will be ok:

printf("((STU *)pVd)->age = %d, ((STU *)pVd)->name = %s \n", ((STU *)pVd)->age, ((STU *)pVd)->name );

 

4. "pVd1 ++;" equivalent to "(char* )pVd1 ++;"
     the increasement is just one byte(GNU support it)
    
5.
"(char* )pVd1 ++;" is ok in GNU
     (char* )pVd1 += 1; ("error: invalid lvalue in assignment")is unsupported in GNU

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值