Data Type in C
Data Type Encapulation
void
means “no type”. void *
means “a pointer with no type”. void *
can point to any type of address.
Usage 1:
void
is to encapulate the data typeint initHardEnv(void ** handle)
. A typical example is memory opertation functions such asmemcpy
andmemset
void * memcpy(void * dest, const void * src, size_t len);
void * memset(void * buffer, int c, size_t num);
Usage 2:
void
is to describe the return value and parameters. It only means “empty” or “nothing”.If a function has no return value, it shall declare the return value as
void
;if a function has no parameter, it shall declare the parameter to be
void
.Example:
void function(void){ ... }
meaning of
void
pointerIn C, only the same type of pointers can be mutally assigned to each other.
void *
pointer used as left operand will accept an a pointer assignment of any typesvoid *
pointer used as right operand doing the pointer assignment has to be exclusively casted to the specific type on intentionExamples:
1
2int * p1 = null;
char * p2 = (char*)malloc(sizeof(char)*20);
C does not support
void
type variable
Pointer
Pointer is also a data type. It has 8 principles.
1. Pointer is a Data Type
- Pointer is a variable. It occupies memory space to store a memory address.
1 | int main(int argc, const char * argv[]) { |
*p
can manupate the memory space.- When declearing the pointer, we use
*
to claim the varialble it modifies is a pointer. - When use the pointer, we use
*
to update or access the value that the pointer points to in the memory space. - The left operand of
*p
means assignment, i.e. assign a value to a memory slot. - The right operand of *p means to retrieve the value from the memory slot.
- When declearing the pointer, we use
- The pointer variable is different from the memory slot the it points to.
- Making
p=0X1111
will only change the pointer variable’s value. It won’t change the value thatp
points to. - Making
*p='a';
will only change the value it points to, but not change the value of the pointer variable. - If a pointer points to memory value stored in the global constant memory space, the value of that memory can’t not be changed.
- Making
1 | // insert code here... |
The output the above is as following:
1 | the value of p1: -272632532 |