Page Content

Tutorials

What Are The C Pointers & How To Declare Pointer Variables?

Overview of C Pointers

A variable that holds the memory address of another variable or piece of data is called a pointer. A pointer stores the address where a value is kept in the computer’s memory rather than the value itself, as a standard variable would. Indirection is the process of referring to an item using a reference.

One of C’s most potent features is said to be pointers. Among their goals are:

  • Allowing called functions to change variables in the calling routine by enabling pass-by-reference for functions. Arguments in C are usually supplied by value.
  • Functions being passed to other functions.
  • Efficiently working with arrays and strings. The link between arrays and pointers is intimate.
  • Constructing and working with dynamic data structures that can expand and contract while a program is running, such as linked lists, queues, stacks, and trees.
  • Use dynamically allocated memory.
  • Facilitating notation and increasing program efficiency, which frequently leads to speedier and less memory-intensive code, especially when arrays are used.
  • Providing programmers with extensive access to and control over the computer’s memory, which is crucial for systems programming.

Knowing how to define a variable that can store addresses and how to get a variable’s memory address are prerequisites for working with pointers.

Accessing the Address of a Variable

The operand’s memory address can be obtained using the unary address operator (&). For instance, the expression &x returns the address in memory where the value of x is kept if you have a variable int x;. Expressions, constants, and register variables are not affected by the address operator; it only applies to variables and array items.

Declaring Pointer Variables

Pointer variables need to be defined before they may be utilised, just like any other variable. Pointer declarations define the memory location’s data type. Data_type *ptr_name; declares a pointer variable.

  • Data_type indicates the object the pointer points to.
  • The asterisk indicates a pointer variable. Int *p; declares p as an integer pointer variable. The type int indicates the variable to which the pointer is pointed, not its value.
  • With several declarations on a line, you must declare each pointer variable separately since the * only applies to the next variable. Int *countPtr, count; for example, declares count as a standard integer but countPtr as a pointer to an integer.

Initializing Pointer Variables

When a pointer variable is declared or later given a value, it can be initialised. An address, NULL, or 0 can be used to initialise a pointer.

  • Int x; int *p = &x; declares x as an integer, p as a pointer to an integer, and initialises p with the address of x. This is a popular way to assign a variable’s address.
  • Nothing is pointed to by a pointer with the value NULL. The symbolic constant NULL has the value 0. A pointer is initialised to NULL if it is initialised to 0. Since NULL highlights that the variable is of the pointer type, it is typically preferred over 0 for clarity. The only integer value that can be directly assigned to a pointer variable is 0.
  • Initialising pointers is crucial to avoiding errors and unexpected outcomes. Data may be written to an unidentified memory location if an uninitialised pointer is used. Before a variable’s address is allocated to a pointer variable, the variable must be defined.

Example:

How to set the address of an integer variable (x) to an integer (ip = &x;) and define a pointer to an integer (int *ip;):

int x = 1, y = 2, z;
int *ip;         /* ip is a pointer to int */
ip = &x;        /* ip is now points to x */
ip = &y;        /* ip is now points to y */
ip = &z;     /* ip is now points to z */

Dereferencing Pointers

Learn how to access the value stored at the memory address that a pointer points to by using the dereference (or indirection) operator (*).

The unary indirection operator (*), commonly known as the dereferencing operator or “value at address” operator, allows you to access the value stored at the address of another variable once a pointer variable has that address. The value of the object to which a pointer points can be obtained by applying the * operator to a pointer operand.

For example, given:

int i = 42; int *pi = &i; // pi now holds the address of i

The value of i (42) that is stored at the address contained in pi is denoted by the phrase *pi.

int j = *pi; // j is initialized to 42 by using pi to obtain the value.

If the pointer does not restrict it (for example, by using const), the dereference operator permits both reading the value and writing to the memory location referred to.

*pi = 50; // The variable i (pointed to by pi) is now set to 50

An error occurs when a pointer is de-referenced without being initialised with or assigned the address of another variable in memory.

Pointer Operations

With the help of code examples, learn the fundamental pointer operations in C, such as assignment and arithmetic.

Pointer variables can be utilised in expressions just like other variables. Pointers can be used for a small number of arithmetic and comparison operations.

  • Assignment: As previously demonstrated, you can use the & operator to assign a variable’s address to a pointer variable. Assigning the value of one pointer variable to another of the same type is another option. Both points will point to the same memory address following the assignment.
  • Pointer Arithmetic: The only arithmetic operations that may typically be carried out on pointers are addition and subtraction. These consist of:
    • You can either increment (++) or decrement (–).
    • Giving a pointer (+ or +=) an integer.
    • Taking an integer and subtracting it from a pointer (- or -=).
    • One pointer is subtracted from another.
  • An number multiplied by the size of the data type the pointer corresponds to is added or subtracted from a pointer, changing the pointer’s address value. For instance, ptr++ would move the pointer to refer to position 1004 (1000 + 1 * 4) if an int* points to address 1000 and integers are 4 bytes.
  • The main application of pointer arithmetic is when the pointer points to an array’s elements. It is possible to think of an array’s name as a pointer to its first element. Array subscript notation (arrayName[offset] or pointerToElement[offset]) is equal to pointer/offset notation (*(arrayName + offset) or *(pointerToElement + offset)), which is used to access array items.
  • Only when both points point to the same array does subtracting one from the other make sense. The amount of items between two such pointers is the consequence of subtracting them.
  • A logic error occurs when pointer arithmetic is performed on pointers that do not refer to array elements. Pointers must be used carefully to make sure they point to a legitimate memory address before being used. Program faults can arise when an uninitialised pointer is used.

Example: Pointer Increment and Decrement

#include <stdio.h>
// pointer increment and decrement
//pointers are incremented and decremented by the size of the data type they point to 
int main()
{
    int a = 22;
    int *p = &a;
    printf("p = %u\n", p); // p = 6422288
    p++;
    printf("p++ = %u\n", p); //p++ = 6422292    +4   // 4 bytes
    p--;
    printf("p-- = %u\n", p); //p-- = 6422288     -4   // restored to original value
    float b = 22.22;
    float *q = &b;
    printf("q = %u\n", q);  //q = 6422284
    q++;
    printf("q++ = %u\n", q); //q++ = 6422288      +4   // 4 bytes
    q--;
    printf("q-- = %u\n", q); //q-- = 6422284       -4  // restored to original value
    char c = 'a';
    char *r = &c;
    printf("r = %u\n", r);   //r = 6422283
    r++;
    printf("r++ = %u\n", r);   //r++ = 6422284     +1   // 1 byte
    r--;
    printf("r-- = %u\n", r);   //r-- = 6422283     -1  // restored to original value
    return 0;
}

Output:

p = 1441900792
p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791
r++ = 1441900792
r-- = 1441900791

Example: Addition of Integer to Pointer

// C program to illustrate pointer Addition
include
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
printf("Pointer ptr2 before Addition: ");
printf("%p \n", ptr2);
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after Addition: ");
printf("%p \n", ptr2);
return 0;
}

Output:

Pointer ptr2 before Addition: 0x7ffca373da9c 
Pointer ptr2 after Addition: 0x7ffca373daa8 

Example: Taking an integer and subtracting it from a pointer (- or -=)

#include <stdio.h>
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr + 4; // ptr points to the last element (50)
    printf("Initial pointer value (address of arr[4]): %p\n", ptr);
    printf("Value at initial pointer location: %d\n", *ptr); // Output: 50
    // Subtracting an integer from the pointer using -
    int *new_ptr = ptr - 2; // Move the pointer 2 integer positions backward
    printf("\nPointer value after subtraction (ptr - 2): %p\n", new_ptr);
    printf("Value at new pointer location: %d\n", *new_ptr); // Output: 30
    // Subtracting and assigning using -=
    ptr -= 1; // Move the original pointer 1 integer position backward
    printf("\nPointer value after subtraction and assignment (ptr -= 1): %p\n", ptr);
    printf("Value at original pointer location: %d\n", *ptr); // Output: 40
    return 0;
}

Output:

Initial pointer value (address of arr[4]): 0x7fffffffdc58
Value at initial pointer location: 50
Pointer value after subtraction (ptr - 2): 0x7fffffffdc50
Value at new pointer location: 30
Pointer value after subtraction and assignment (ptr -= 1): 0x7fffffffdc54
Value at original pointer location: 40

You can also read What Is The Scope And Lifetime Of Variables In C?

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index