Go back

Data Structures and Algorithms - More About Pointers

Address of operator: & Example: int y = 10; int *x = &y; Here the & operator gets the address of the variable y and stores it in the pointer x.

Indirection operator: * it is used to access and update the value stored at the address which is stored in the pointer this operator is being used for.

Function pointer

We can use a function pointer to pass a function to another function like a variable.

To declare a function pointer we write it as

return_type *function_name(parameter_1_type, parameter_2_type...)

Example:

#include<stdio.h>

int add(int a, int b){
    return a+b;
}


int subtract(int a, int b){
    return a-b;
}


// here f is a function pointer
int operation(int a, int b, int *f(int,int)){
    return f(a,b);
}


int main(){
    int x = 5,y = 3,z,w;

    z = operation(x,y,add); //passing the add function to the function poitner
    w = operation(x,y,subtract); //passing the subtract function to the pointer

    printf("%d,%d",z,w);
    return 0;
}

You can use function pointers to pass functions for sorting to a sorting function.

Call by value vs Call by reference

Call by Value:

In call by value, a copy of the actual parameter is passed to the function. Changes made inside the function do not affect the original value of the variable.

#include <stdio.h>

void inc(int x) {
    x++; //this change will only be in this function but not to the actual varibel
}

int main() {
    int a = 5;
    inc(a);
    printf("Value of a: %d\n", a); // Output: 5
    return 0;
}

Call by Reference:

In call by reference, the address of the actual parameter is passed to the function. Changes made inside the function directly modify the original variable.

Example:

#include <stdio.h>

void inc(int *x) {
    (*x)++; //this change will change the varibel x
}

int main() {
    int a = 5;
    inc(&a);
    printf("Value of a: %d\n", a); // Output: 6
    return 0;
}

Pointer to structure

#include<stdio.h>
#include<string.h>

struct cat{
    int a;
    char b[10];
};

int main(){
    struct cat x;
    struct cat *y; //this is a pointer to the structure
    x.a = 10;
    strcpy(x.b, "Hello");

    //to access the values inside the struct pointer we use the -> operator
    printf("%d", y->a);
    fputs(y->b);
    return 0;
}

Pointer to pointer

As the name suggests, pointer to pointer is a pointer which sotres the address of another pointer.

int **x; //this is a pointer to an integer pointer
int *y;
int z = 10;
y = &z;
x = &y; // the pointer to pointer x stores the address of the variable y

Finally the meme you have been waiting for -

Pointer to pointer with anya