Loading . . .

C Programming in VS Code

Printing a message in C

Beginner's Guide to Keywords, Identifiers, Constants, Variables, Datatypes in C

Operators & Expressions in C

Input & Output Operations in C

Control Statements in C

Loops in C

Array in C

Character Array & Strings in C

User Defined Functions in C

Structure and Union in C

Pointers in C


Disclaimer: Educational Purposes Only

The content on this website, including videos and code examples, is for educational purposes only. All demonstrations and designs are fictional and created to illustrate coding techniques. Any resemblance to existing websites or brands is purely coincidental.

The creators and administrators of this website do not claim ownership or affiliation with any existing websites or companies. Users are encouraged to use the information responsibly for learning purposes. Liability for any misuse of the content provided is not accepted.

Download Notes

Pointers in C

Pointers: Pointers contain memory addresses as their values. Since these memory addresses are the locations in the computer memory where program instructions and data are stored, pointers can be used to access and manipulate data stored in the memory.

Benefits of Pointers:

1) Pointers are more efficient in handling arrays and data tables.

2) Pointers can be used to return multiple values from a function via function arguments.

3) Pointers permit references to functions and thereby facilitate the passing of functions as arguments to other functions.

4) The use of pointer arrays to character strings results in the saving of data storage space in memory.

5) Pointers allow C to support dynamic memory management.

6) Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees.

7) Pointers reduce the length and complexity of programs.

8) They increase the execution speed and thus reduce the program execution time.

Accessing the address of a variable: This can be done with the help of the operator "&" available in C. We have already seen the use of this address operator in the scanf function. The operator & immediately preceding a variable returns the address of the variable associated with it.

Declaring pointer variables: In C, every variable must be declared for its type. Since pointer variables contain addresses that belong to a separate data type, they must be declared as pointers before we use them.

Pointer Declaration Style:

1) int* p;

2) int *p;

3) int * p;

Initialization of Pointer Variables: The process of assigning the address of a variable to a pointer variable is known as initialization. Uninitialized pointers will produce erroneous results. Once a pointer variable has been declared we can use the assignment operator to initialize the variable.

Accessing a variable through its pointer: This is done by using another unary operator *(asterisk), usually known as the indirection operator or dereferencing operator.

Chain of Pointers: It is possible to make a pointer point to another pointer, thus creating a chain of pointers. Pointer "p2" contains the address of the pointer variable "p1", which points to the location that contains the desired value. This is known as multiple indirections. A variable that is a pointer to a pointer must be declared using additional indirection operator symbols in front of the name.

Rules of pointer operations:

1) A pointer variable can be assigned the address of another variable.

2) A pointer variable can be assigned the values of another pointer variable.

3) A pointer variable can be initialized with a NULL or zero value.

4) A pointer variable can be pre-fixed or post-fixed with increment or decrement operators.

5) An integer value may be added or subtracted from a pointer variable.

6) When two pointers point to the same array, one pointer variable can be subtracted from another.

7) When two pointers point to the objects of the same data types, they can be compared using relational operators.

8) A pointer variable cannot be multiplied by a constant.

9) Two pointer variables cannot be added.

10) A value cannot be assigned to an arbitrary address (i.e, &x = 10; is illegal).

Pointers and arrays/strings: As we already know the pointer has the base address of the variable so in the case of arrays/strings the base address is index 0. To traverse the array/string we need to do an increment in the pointer to move to the next address (i.e index 1).

Pointers as function arguments: When we pass addresses to a function, the parameters receiving the addresses should be pointers. The process of calling a function using pointers to the addresses of variables is known as "call by reference". (The process of passing the actual value of variables is known as "call by value".) The function which is called by "reference" can change the value of the variable used in the call.

Note:

1) The function parameters are declared as pointers.

2) The dereferenced pointers are used in the function body.

3) When the function is called, the addresses are passed as actual arguments.

Functions returning pointers: We have seen so far that a function can return a single value by its name or return multiple values through pointer parameters. Since pointers are a datatype in C, we can also force a function to return a pointer to the calling function.

Pointers to functions: A function, like a variable, has a type and an address location in the memory. It is, therefore, possible to declare a pointer to a function, which can then be used as an argument in another function. This tells the compiler that "function_pointer" is a pointer to a function, which returns a type value. The parentheses around "*function_pointer" are necessary.

Pointers and structures: A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure. The use of a structure pointer to manipulate the elements of an array of structures.

Troubles with pointers:

1) Assigning values to uninitialized pointers.

2) Assigning value to a pointer variable.

3) Not dereferencing a pointer when required.

4) Assigning the address of an uninitialized variable.

5) Comparing pointers that point to different objects.

Pointers in C

Accessing the address of variable:

accessing_the_address_of_variable.c


#include <stdio.h>

void main() {
    char a = 'A';
    int b = 10;
    printf("%c is stored at %u\n%d is stored at %u", a, &a, b, &b);
}

Initializing pointer variable:

initializing_pointer_variable.c


#include <stdio.h>

void main() {
    int a, *p; // declaration
    p = &a; // initialization
    printf("Enter a number: ");
    scanf("%d", &a);
    printf ("\nNumber you entered: %d and stored at %u", *p, p);
}

Accessing variable through pointer:

accessing_variable_through_pointer.c


#include <stdio.h>

void main() {
    int x = 10, y, *p;
    p = &x;
    y = *p;
    printf("Value of x is %d\n", x);
    printf("%d is stored at address %u\n", x, &x);
    printf("%d is stored at address %u\n", *&x, &x);
    printf("%d is stored at address %u\n", *p, p);
    printf("%d is stored at address %u\n", p, &p);
    printf("%d is stored at address %u\n", y, &y);
    *p = 25;
    printf("Now x = %d", x);
}

Pointer and arrays/strings:

pointer_and_arrays_strings.c


#include <stdio.h>

void main() {
    int *p, sum, i, x[5] = {1, 2, 3, 4, 5};
    p = x;
    printf("Element\t\tValue\t\tAddress\n");
    for (i = 0; i < 5; i++) {
        printf("x[%d]\t\t%d\t\t%u\n", i, *p, p);
        sum += *p;
        p++;
    }
    printf("\nSum = %d\n&x[0] = %u\np = %u", sum, &x[0], p) ;
}

Pointer as function:

pointer_as_function.c


#include <stdio.h>

void swap(int *, int *); // prototype

void main() {
    int x = 100, y = 200;
    printf("Before Swap:\n\tx = %d\ty = %d\n", x, y);
    swap(&x, &y);
    printf("After Swap:\n\tx = %d\ty = %d", x, y);
}

void swap(int *a, int *b) {
    int t;
    t = *a; // assign the value at address a to t
    *a = *b; // put b into a
    *b = t; // put t into b
}

Function returning pointers:

function_returning_pointers.c


#include <stdio.h>

int *larger(int *, int *);

void main() {
    int a = 10, b = 20, *p;
    p = larger(&a, &b);
    printf("%d is larger.", *p);
}

int *larger(int *x, int *y) {
    if (*x > *y) {
        return (x); // address of x
    } else {
        return (y); // address of y
    }
}

Pointer to function:

pointer_to_function.c


#include <stdio.h>

void value(int a) {
    printf("Value of a is %d", a);
}

void main() {
    void (*print)(int) = &value;
    (*print)(10);
}

Pointer and structure:

pointer_and_structure.c


#include <stdio.h>

struct student {
    int roll_no;
    char name[10];
};

void main() {
    struct student s, *p;
    p = &s;
    printf("Enter the name of student: ");
    scanf("%s" , &p->name) ;
    printf("\nEnter the roll no: ");
    scanf("%d", &p->roll_no) ;
    printf("\nYou entered:\n\tStudent Name: %s\t\tRoll no: %d", p->name, p->roll_no);
}