Pointer declaration and initialization

Home / C Programming / Pointer declaration and initialization

Pointer declaration and initialization


In C programming, pointers are variables that store memory addresses. They allow you to indirectly access and manipulate data by pointing to the memory location where the data is stored. The declaration and initialization of pointers involve specifying the data type of the variable they point to and assigning the memory address of another variable to the pointer.

Here's how you declare and initialize pointers in C:

Declaration of a pointer:

To declare a pointer, you use the asterisk (*) symbol before the variable name. The syntax is as follows:

data_type *pointer_name;

For example, to declare a pointer to an integer, you would do:

int *ptr; // Declares a pointer to an integer

Initialization of a pointer:

After declaring a pointer, you should initialize it with a memory address where it points to valid data. This is usually done using the address-of operator (&) on another variable. The syntax for initialization is:

pointer_name = &variable_name;

Here's an example:


The output will be:

Value of num: 42

Value pointed by ptr: 42

Remember that uninitialized pointers (pointers without an assigned memory address) will contain garbage values, so always initialize them before using them to avoid unexpected behavior and potential crashes.