AlphaCodingSkills

C - Pointers


Advertisements

Previous Page Next Page

In C, pointer is an important concept to learn. There are few tasks which can be easily performed with the use of pointers and few other tasks like dynamic memory allocation which can not be performed without the use of pointers.

A pointer is a variable which stores address of another variable.

Address-of operator (&)

The address of a variable can be obtained by using ampersand sign (&), known as address-of operator followed by the name of a variable. Please see the syntax below:

Syntax


//p1 is a pointer
//which stores address of variable named MyVariable
p1 = &MyVariable;

Dereference operator (*)

The value of a variable can also be accessed by using pointer. The * operator, known as dereference operator followed by the name of the pointer gives the value stored in the address pointed by the pointer. Please see the syntax below:

Syntax


//p1 is a pointer of variable called MyVariable
//p1 stores address of MyVariable
//*p1 gives value of MyVariable
p1 = &MyVariable;
x = *p1;

Declare pointer

The declaration of a pointer starts with datatype pointed to by the pointer followed by * and name of the pointer. The datatype is not the datatype of the pointer itself, but the datatype of the data the pointer points to. Please see the syntax below:

Syntax


int *p1;     //pointer to an integer
double *p1;  //pointer to a double
float *p1;   //pointer to a float 
char *p1;    //pointer to a character

//multiple declaration of pointers 
//p1 and p2 are pointers declared in a single line
int *p1, *p2; 

//below, p1 is pointer
//and p2 is integer datatype variable not pointer 
int *p1, p2 

Example:

In the below example, an integer variable called MyVar and a pointer called p1 are created. pointer p1 is assigned the address of MyVar using address-of (&) operator. The dereference operator (*) is used with p1 to get the value of MyVar as shown in the output.

#include <stdio.h>

int main (){
    int MyVar = 10;
    int *p1;
    p1 = &MyVar;
    printf("%p\n",p1); 
    printf("%i",*p1);
    return 0;
}

Output

0x7ffed13c2db4

10





Previous Page Next Page