Pointers in C

What is pointer?

Pointers are an essential concept in programming, especially in languages like C and C++. Pointers are variables that store memory addresses. They allow you to access and manipulate data stored in memory, including variables, arrays, and structures.

When you declare a variable in C or any programming language, the system allocates a block of memory to store the value of that variable. This block of memory has a unique address, which you can access using a pointer



memory allocation

pointer declaration

For example, let's say you have a variable called "x" that stores an integer value. You can declare a pointer called "ptr" to store the memory address of "x" as follows:

int x = 10;
int *ptr = &x;

In this example, the "&" operator is used to get the memory address of "x", which is then stored in "ptr". The "*" operator is used to declare "ptr" as a pointer variable of type "int".


Basic uses of pointers

Once you have a pointer variable, you can use it to access the value of the variable it points to or change that value. For example, you can print the value of "x" using the pointer as follows:

int main() {
  int x = 10;
  int *ptr = &x;

  // Accessing the value of the variable that ptr points to
  printf("The value of x is: %d\n", *ptr);//print value 10

  // Changing the value of the variable that ptr points to
  *ptr = 20;
  printf("The new value of x is: %d\n", x);//print value 20

  *ptr += 100;
   printf("The new value of x is: %d\n", x);//print value 120

   *ptr *= *ptr;
   printf("The new value of x is: %d\n", x);//print value 14400 (120 * 120)

  return 0;
}

In this example, we declare an integer variable ‘x’ and a pointer variable ‘ptr’ that points to the address of ‘x’. We then use the ‘*’ operator to access the value of ‘x’ using the pointer ‘ptr’, and print it to the console using ‘printf()’.

Next, we change the value of ‘x’ by assigning a new value to the variable that ‘ptr’ points to using the ‘*’ operator. Finally, we print the new value of ‘x’ to the console using ‘printf()’.


Array operations with pointers

1.Accessing array elements: You can access individual elements of an array using   pointers by using pointer arithmetic. For example, to access the first element of an array 'arr' using a pointer 'ptr', we can write:
int* ptr = arr;
int first_element = *ptr;
Here, the first line sets the pointer ptr to the address of the first element of the array arr. The second line uses the * operator to access the value of the first element.


2.Iterating over an array: You can use a pointer to iterate over an array by using pointer arithmetic. For example, to print all the elements of an array 'arr', you can write:
int* ptr = arr;
for (int i = 0; i < array_length; i++) {
    printf("%d ", *ptr);
    ptr++;
}

Here, the pointer ptr is initialized to the address of the first element of the array arr. Inside the loop, the value of the current element is printed using the * operator, and the pointer is incremented to point to the next element.



3.Passing arrays to functions: You can pass arrays to functions using pointers. For example, to pass an array 'arr' to a function 'insert_begining', we can write:
void insert_begining(int *arr,int lenth,int value){
    for (int i = lenth -1; i > 0; i--)
    {
        arr[i]=arr[i-1];
    }
    *arr = value;
}

void main(){
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
    int len = sizeof(arr)/sizeof(arr[0]);

    for (int i = 0; i < len; i++)
    {
        printf("%d ",arr[i]);
    }//output 1 2 3 4 5 6 7 8 9 10
    
    printf("\n");
    insert_begining(arr,len,100);

    for (int i = 0; i < len; i++)
    {
        printf("%d ",arr[i]);
    }//output 100 1 2 3 4 5 6 7 8 9
    
}
Here, the array 'arr' is passed to the function 'insert_begning' as a pointer to the first element of the array. The length of the array is also passed as a separate argument.



4.Returning arrays from functions: You can return arrays from functions using pointers. For example, to return an array 'arr' from a function 'my_function', we can write:
int *my_function(int array_length)
{
    int *arr = (int *)malloc(array_length * sizeof(int));
    if (arr == NULL)
    {
        printf("Error: could not allocate memory.\n");
        exit(1);
    }
    for (int i = 0; i < array_length; i++)
    {
        arr[i] = pow(2,i);
    }
    return arr;
}
Here, the function 'my_function' takes an integer 'array_length' as an argument and allocates an array of 'array_length' integers using 'malloc'. If 'malloc' returns a null pointer, the function prints an error message and exits with a non-zero status code. 
The function then fills in the array with the values '1' through 'array_length', and returns a pointer to the first element of the array. 
To call this function and use the returned array, we can do the following:

int array_length = 5;
int* my_array = my_function(array_length);
for (int i = 0; i < array_length; i++) {
    printf("%d ", my_array[i]);
}
free(my_array);
Here, 'array_length' is set to '5', and 'my_function' is called with 'array_length' as an argument. The function returns a pointer to the first element of the allocated array, which is stored in the variable 'my_array'.
The elements of the array are printed using a loop and the 'printf' function. 
Finally, the memory allocated by 'malloc' is freed using the 'free' function. This is important to avoid memory leaks.

Comments