Like variables, pointers have to be declared before they can be used in your program. Pointers can be named anything you want as long as they obey C’s naming rules. A pointer declaration has the following form.
data_type * pointer_variable_name;
- data_type is the pointer’s base type of C’s variable types and indicates the type of the variable that the pointer points to.
- The asterisk (*: the same asterisk used for multiplication) which is indirection operator, declares a pointer.
Let’s see some valid pointer declarations
int *ptr_thing; /* pointer to an integer */
int *ptr1,thing;/* ptr1 is a pointer to type integer and thing is an integer variable */
double *ptr2; /* pointer to a double */
float *ptr3; /* pointer to a float */
char *ch1 ; /* pointer to a character */
float *ptr, variable;/*ptr is a pointer to type float and variable is an ordinary float variable */
Initialize a pointer
After declaring a pointer, we initialize it like standard variables with a variable address. If pointers are not uninitialized and used in the program, the results are unpredictable and potentially disastrous.
To get the address of a variable, we use the ampersand (&)operator, placed before the name of a variable whose address we need. Pointer initialization is done with the following syntax.
pointer = &variable;
A simple program for pointer illustration is given below:
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf(“Address stored in a variable p is:%x\n”,p); //accessing the address
printf(“Value stored in a variable p is:%d\n”,*p); //accessing the value
Address stored in a variable p is:60ff08
Value stored in a variable p is:10
|*||Serves 2 purposeDeclaration of a pointerReturns the value of the referenced variable|
|&||Serves only 1 purposeReturns the address of a variable|