/* 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