C Pointer Comparison 🎯

beginner
21 min

C Pointer Comparison 🎯

Welcome to another engaging tutorial at CodeYourCraft! Today, we're diving into a fundamental aspect of C programming: Pointers. This lesson is designed for beginners and intermediates, so let's get started!

What are Pointers? 📝

Pointers are variables that store the memory addresses of other variables. They are used to indirectly access and manipulate data in memory.

c
int number = 10; int *ptr; // Here, ptr is a pointer variable that can store the address of an int variable ptr = &number; // Here, we assign the address of number to ptr

In the above example, ptr now points to the memory location where number is stored.

Pointer Types 📝

C provides various types of pointers, each designed for specific data types:

  1. int *ptr for integers
  2. char *ptr for characters
  3. float *ptr for floats
  4. double *ptr for doubles
  5. void *ptr for void type

Pointer Operations 📝

Pointers can perform several operations:

  • Dereferencing: Accessing the value stored at the memory address pointed by a pointer using the * operator.
c
int number = 10; int *ptr = &number; printf("%d", *ptr); // Output: 10
  • Incrementing/Decrementing: Increasing or decreasing the memory address that a pointer points to using the ++ and -- operators.
c
int number = 10; int *ptr = &number; printf("%d", *ptr); // Output: 10 ptr++; printf("%d", *ptr); // Output: 11

Pointer Arithmetic 📝

Pointer arithmetic involves performing mathematical operations on pointers.

  • Addition: Adding an integer to a pointer moves the pointer by the size of the pointed data type multiplied by the integer.
c
int numbers[5] = {1, 2, 3, 4, 5}; int *ptr = numbers; printf("%d", *(ptr + 2)); // Output: 3
  • Subtraction: Subtracting a pointer from another gives the difference in their memory addresses.
c
int numbers[5] = {1, 2, 3, 4, 5}; int *ptr1 = numbers; int *ptr2 = &numbers[3]; printf("%d", (ptr2 - ptr1)); // Output: 3

Pointers and Memory Allocation 📝

Pointers play a crucial role in memory allocation using malloc() and calloc() functions.

c
int size = 10; int *ptr = (int *) malloc(size * sizeof(int)); if (ptr != NULL) { // Use ptr to store and access data here // ... free(ptr); // Don't forget to free the allocated memory! }

Pointer Quiz 💡

Quick Quiz
Question 1 of 1

What is the output of the following code?

By now, you should have a solid understanding of pointers in C programming. Happy coding! 🥳