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 type

    • int initHardEnv(void ** handle). A typical example is memory opertation functions such as memcpy and memset
      • 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 pointer

    • In 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 types

    • void * pointer used as right operand doing the pointer assignment has to be exclusively casted to the specific type on intention

      Examples:

      1
      2
      int * 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
2
3
4
5
int main(int argc, const char * argv[]) {
// insert code here...
int * p1 = 100; // to tell the compiler to allocate 8 bytes of memory space
return 0;
}
  • *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.
  • 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 that p 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.
1
2
3
4
5
6
7
8
// insert code here...
int x = 2;
int * p1 = &x; // to tell the compiler to allocate 8 bytes of memory space

printf("the value of p1: %d\n", p1);

int * p2 = 3; // this assignment is misleading and not recommended, because you are assigning an int value to pointer variable.
printf("the value of p1: %d\n", p2);

The output the above is as following:

1
2
the value of p1: -272632532
the value of p1: 3