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!
Pointers are variables that store the memory addresses of other variables. They are used to indirectly access and manipulate data in memory.
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 ptrIn the above example, ptr now points to the memory location where number is stored.
C provides various types of pointers, each designed for specific data types:
int *ptr for integerschar *ptr for charactersfloat *ptr for floatsdouble *ptr for doublesvoid *ptr for void typePointers can perform several operations:
* operator.int number = 10;
int *ptr = &number;
printf("%d", *ptr); // Output: 10++ and -- operators.int number = 10;
int *ptr = &number;
printf("%d", *ptr); // Output: 10
ptr++;
printf("%d", *ptr); // Output: 11Pointer arithmetic involves performing mathematical operations on pointers.
int numbers[5] = {1, 2, 3, 4, 5};
int *ptr = numbers;
printf("%d", *(ptr + 2)); // Output: 3int numbers[5] = {1, 2, 3, 4, 5};
int *ptr1 = numbers;
int *ptr2 = &numbers[3];
printf("%d", (ptr2 - ptr1)); // Output: 3Pointers play a crucial role in memory allocation using malloc() and calloc() functions.
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!
}What is the output of the following code?
By now, you should have a solid understanding of pointers in C programming. Happy coding! 🥳