C Tutorial -- Pointer

Pointer? Easy(again…)! Let’s talk about it! What is pointer?

C Pointers

What’s pointer?

A pointer is a variable whose value is the address of another variable, that is, the direct address of a memory location.

Declare pointers

​ So, just like other variables or constants, you must declare pointers before storing the addresses of other variables:

type *var-name;

​ The asterisk * used to declare pointers is the same as the asterisk used in multiplication. However, in this statement, the asterisk is used to specify that a variable is a pointer.

​ Examples:

int    *ip;
double *dp;
float  *fp;
char   *ch;

The only difference between pointers of different data types is that the data types of the variables or constants pointed to by the pointers are different.

How to use pointers?

​ Talk is cheap, show the code:

#include <stdio.h>
 
int main ()
{
   int  var = 10;
   int  *p;
 
   p = &var;
 
   printf("var address: %p\n", &var);
   printf("p address: %p\n", p);
   printf("*p: %d\n", *p );
 
   return 0;
}

​ results:

var address: 000000000022FE44
p address: 000000000022FE44
*p: 10
    

NULL pointer in C

​ During variable declaration, if there is no exact address to assign, it is a good programming practice to assign a NULL value to the pointer variable. A pointer assigned a NULL value is called a null pointer.

#include <stdio.h>
 
int main ()
{
   int  *p = NULL;
 
   printf("p address: %p\n", p);
 
   return 0;
}

​ result:

p address: 0x0
    

​ On most systems, programs are not allowed to access the memory at address 0, because the memory is reserved by the operating system. However, the memory address 0 has a particularly important meaning, it indicates that the pointer does not point to an accessible memory location. But by convention, if the pointer contains a null value, it is assumed to point to nothing.

Check for null pointers

​ We often use if to check for pointers:

if(!p)	//if p is null
{
	...
}

or

if(p)	//if p is not null
{
	...
}

Pointer


© 2020-2021. All rights reserved.