Ishaare

How to point using the C language?

ยท

3 min read

Ishaare

This piece serves as an intro to pointers in the C language. I have tried to present this intricate topic in a simple manner.

Enjoy ๐Ÿ˜Š

\* If you have any queries, feel free to put those in the comments*


Variables: A Refresher

Every variable in C has a name and a value. Consider

int a = 9;

When the above statement executes, a chunk of memory (4 bytes in this case) is allocated to store the value 9. The compiler also sets up a symbol table, in which it adds the symbol a with its corresponding memory address (it refers to the location where the 4 bytes were set aside). Thus, every variable is also associated with an address.

N.B. The value of a variable always appears on the right side of the assignment operator. Extending the above line of code,

int b = a;

Here, a refers to the value stored in the memory space allotted to a. So now, b is also 9.

Pointers

A pointer is a variable that stores the memory address of another variable or array.

type *name; (pointer declaration)

type refers to the data type of the variable that the pointer is "pointing to".

#include<stdio.h>
int main()
{
    int num = 7, *ptr;
    ptr = &num;     
    printf("Address: %p \n", ptr);
    printf("Value: %d \n", *ptr); 
    return 0;
}
  • Once declared, *ptr refers to the value in the memory address assigned to it.

  • The address of a variable cannot be changed.

Arrays

Imagine any int array a[] The following bullets elucidates its connection to pointers:

  • The name, a, of the array is known as the base address, it refers to the address of the first element, a[0]

  • int *pa = a; assigns the address of a[0] to the pointer. To mutate pa, use pa += i, which re-assigns pa with the address of a[i].

  • Syntax sugar:a[i] is equivalent to *(a + i)

๐Ÿ“Œ Misconception

Some think that the array name is a pointer, but an assignment like a = pa is invalid. This is because pa is a variable, whereas a is a constant. Once a[] has been declared, the memory address allocated to a[0] is immutable. Hence, the array name can be thought of as a constant pointer.

๐Ÿ“Œ Pointer Arithmetic

  • We can add integers to a pointer to get a new pointer that stores the address of a different location than the original pointer. Let pa1 and pa2 be two int pointers. Say pa1 = &a[1] , then pa2 = pa + 3 points to a[4].

  • It is possible to subtract two pointers, provided they are pointing to the same array. E.g., printf("%ld", pa2 - pa1); gives 3, which is the number of elements between pa1 and pa2.

  • We can also use relational operators with pointers. If pa1 < pa2 , it means pa1 is pointing to an element nearer to the beginning (index 0) than pa2.


Grateful for your attention ๐Ÿ˜Š

๐Ÿ“ For more code snippets

See ya ๐Ÿฉต

ย