C Pointers

Pointers are very useful in C and C++ programming. A pointer is a variable that stores address of another variable instead of the value. Pointers are very powerful as they have direct memory access which makes them a threat to security. Wrong usage of pointers can cause program to crash or give abnormal output.

Declaring a Pointer


data_type* ptr;
data_type *ptr;

Address of a variable using Dereference Operator


int *ptr;
int x = 10;
//p holds the address of x
p = &x;

Pointer to an Array

int arr[3] = {0,1,2};  
int *ptr = &arr;

Pointer to a Function

void fun(int a) 
    //do something
void (*func_ptr)(int) = &fun;
/* Equivalent to
    void (*func_ptr)(int); 
    fun_ptr = &fun;  

Pointer to Structure

struct S {  
    int x;
    char b;

struct S *ptr = &s_obj;

NULL Pointer

A null pointer is a pointer which isn't pointing to anything. Null pointers are declared when addresses are not specified or may get specied later in the program.


int *ptr = NULL;

Dangling Pointer

Dangling (or wild) pointer is a pointer that points somewhere, but not to a valid object.


#include <stdlib.h>

int main(void)
    char *ptr = malloc(10);

    free(*ptr);         /* ptr now becomes a dangling pointer */
    ptr = NULL;        /* ptr is now null pointer */

    return 0;


C Programming

Remember to follow community guidelines and don't go off topic.