11
OctPointers in C: Types of Pointers
Pointers in C Programming: An Overview
What are Pointers in C?
int
, float
, char
, etc.- By referencing this memory address, programmers can access and modify data indirectly. This property allows dynamic memory allocation and, the ability to pass large data structures to functions without duplicating memory.
- They enable users to create complex data structures, such as linked lists and trees, indispensable in various programming scenarios.
Pointer Declaration in C
*
(asterisk symbol) before a pointer's name.Syntax
int *a;//pointer to int
char *c;//pointer to char
Example of Pointer Declaration in C
#include<stdio.h>
int main(){
int number=120;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
This C code in the C Compiler shows how to access and work with data in memory by declaring an integer variable number
, a pointer p
, and printing the address as well as the value of the number
variable using pointer operations.
Output
Address of number variable is fff4
Value of p variable is 120
Pointer Initialization in C
The procedure of initializing a pointer is where we give the memory address of another variable using the &
(address of) operator.
Example of Pointer Initialization in C
#include <stdio.h>
int main() {
int x = 42; // Declare and initialize an integer variable 'x'
int *ptr = &x; // Declare a pointer 'ptr' and initialize it with the address of 'x'
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", &x);
printf("The value pointed to by ptr: %d\n", *ptr);
return 0;
}
In this C code,
- an integer variable named “
x
” is initialized to42
- a pointer named
ptr
is created to holdx's
address in memory.
Read more: Variables in C Programming
Output
Value of x: 42
Address of x: 0x7ffeedf0
Value pointed to by ptr: 42
Read More - Top 50 Mostly Asked C Interview Questions and Answers
Dereferencing Pointer in C
Dereferencing a pointer involves gaining access to the value kept at the memory address, the pointer specifies. The (*
) dereferencing operator is used just as it was in the pointer declaration.
Example of Dereferencing Pointer in C
#include <stdio.h>
int main() {
int y = 99; // Declare and initialize an integer variable 'y' with a different value
int *ptr = &y; // Declare a pointer 'ptr' and initialize it with the address of 'y'
printf("Value pointed to by ptr: %d\n", *ptr); // Dereferencing 'ptr' to access and print the value of 'y'
return 0;
}
This C code in the C Editor declares a pointer ptr
, initializes an integer variable y
to 99, and then uses dereferencing
to output the value of y
through ptr
.
Output
Value pointed to by ptr: 99
Types of Pointers in C
Depending on the parameters, pointers can be divided into a wide variety of types. The following types of pointers are based on the type of variable that is kept in the memory location that the pointer is pointing to.
Integer Pointers
The memory location of an integer variable is stored in integer pointers.
Syntax
int* intPointer;
Example of Integer Pointers in C
#include <stdio.h>
int main() {
// Declare an integer variable
int num = 42;
// Declare an integer pointer and initialize it with the address of the variable
int *ptr = #
// Access the value using the pointer
printf("Value of num: %d\n", *ptr);
// Modify the value using the pointer
*ptr = 100;
// Display the modified value
printf("Modified value of num: %d\n", num);
return 0;
}
Output
Value of num: 42
Modified value of num: 100
Array Pointer
The initial element of an array may be referenced by array pointers.
Syntax
int arr[5];
int* arrPointer = arr;
Example of Array Pointer in C
#include <stdio.h>
int main() {
// Declare an array
int numbers[] = {10, 20, 30, 40, 50};
// Declare an integer pointer and initialize it with the address of the first element of the array
int *ptr = numbers;
// Access and print elements of the array using the pointer
printf("Array elements using pointer:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, *(ptr + i));
}
// Modify an element of the array using the pointer
*(ptr + 2) = 300;
// Display the modified array
printf("\nModified array elements:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, numbers[i]);
}
return 0;
}
Output
Array elements using pointer:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Modified array elements:
Element 1: 10
Element 2: 20
Element 3: 300
Element 4: 40
Element 5: 50
You will understand this pointer after learning arrays in C.
Structure Pointer
To point to a user-defined datatype, structure
use a structure pointer.
Syntax
struct MyStruct {
int data;
};
struct MyStruct* structPointer;
Example of Structure Pointer in C Online Compiler
#include <stdio.h>
// Define a structure named 'Person'
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declare a structure variable
struct Person person1;
// Declare a pointer to a structure and initialize it with the address of the structure variable
struct Person *ptr = &person1;
// Access and assign values to the structure members using the pointer
printf("Enter name: ");
scanf("%s", ptr->name);
printf("Enter age: ");
scanf("%d", &ptr->age);
printf("Enter height: ");
scanf("%f", &ptr->height);
// Display the information using the pointer
printf("\nInformation using pointer:\n");
printf("Name: %s\n", ptr->name);
printf("Age: %d\n", ptr->age);
printf("Height: %.2f\n", ptr->height);
return 0;
}
Output
Enter name: John
Enter age: 25
Enter height: 175.5
Information using pointer:
Name: John
Age: 25
Height: 175.50
Function Pointers
You can call functions indirectly by using function pointers, that save the address of a function.
Syntax
int (*funcPointer)(int, int);
Example of Function Pointers in C
#include <stdio.h>
// Define two functions with the same signature
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main() {
// Declare a function pointer with the same signature as the functions
int (*operation)(int, int);
// Initialize the function pointer with the address of the add function
operation = add;
// Use the function pointer to call the add function
int result = operation(10, 5);
printf("Result of addition: %d\n", result);
// Reassign the function pointer to the subtract function
operation = subtract;
// Use the function pointer to call the subtract function
result = operation(10, 5);
printf("Result of subtraction: %d\n", result);
return 0;
}
Output
Result of addition: 15
Result of subtraction: 5
Double Pointers
Double pointers are pointers to pointers and are frequently employed in linked data structures or multi-dimensional arrays.
Syntax
int doublePointer;
NULL Pointer
A NULL
pointer is used to signify that a pointer has not been initialized; it points to nowhere in memory.
Syntax
int* nullPointer = NULL;
Example of NULL Pointer in C Online Editor
#include <stdio.h>
int main() {
int *ptr1 = NULL; // Initialize a pointer with NULL
// Attempting to dereference a null pointer will result in undefined behavior
// Uncommenting the line below would lead to a runtime error
// printf("Value at null pointer: %d\n", *ptr1);
if (ptr1 == NULL) {
printf("ptr1 is a null pointer\n");
} else {
printf("ptr1 is not a null pointer\n");
}
// Attempting to free a null pointer is safe
free(ptr1);
// Initializing a pointer with NULL during declaration
int *ptr2 = NULL;
if (ptr2 == NULL) {
printf("ptr2 is a null pointer\n");
} else {
printf("ptr2 is not a null pointer\n");
}
return 0;
}
Output
ptr1 is a null pointer
ptr2 is a null pointer
void Pointer
In general, void pointers can point to any type of data.
Syntax
void* voidPointer;
wild Pointers
wild pointers are dangling or uninitialized pointers that point to arbitrary locations in memory.
Syntax
int *ptr;
char *str;
constant Pointers
Constant pointers direct memory access to a fixed place.
Syntax
const int* constPointer;
Pointer to Constant
A pointer to a constant point to data that the pointer cannot change.
Syntax
int const * pointerToConst;
far Pointer
Early versions of the x86 architecture used far pointers to access extended memory. Today's programming hardly makes use of them.
Syntax
char far *s;
Dangling Pointer
A dangling pointer is a pointer that frequently occurs after the memory it points to has been released or deallocated and points to an incorrect address in memory.
Syntax
int *ptr = malloc(sizeof(int)); // ptr points to a valid memory location
free(ptr); // ptr now points to a dangling memory location
{
int a = 10;
int *ptr = &a; // ptr points to a valid memory location
} // a goes out of scope, ptr now points to a dangling memory location
huge Pointer
In the early x86 architecture, huge pointers were utilized to access enormous memory models. Today's programming hardly makes use of them.
Syntax
int huge *p;
complex Pointer
Depending on the use case, complex pointers may refer to pointers having complex data structures that need a particular syntax.
Syntax
int **p;
near Pointer
Early versions of the x86 architecture employed near pointers to access tiny memory models. Today's programming hardly makes use of them.
Syntax
char near *string;
normalized Pointer
In low-level systems programming, normalized pointers are frequently used to guarantee that the address of the pointer is within the legal address space.
Syntax
int *ptr = _mkptr(0x12, 0x34);
File Pointer
In file I/O operations, file pointers are used to keep track of the current location in a file.
Syntax
FILE* filePointer;
Size of Pointers in C
The sizeof()
function is used to indicate how many bytes of memory are used up in the system. Here, we use the sizeof()
operator to output the size of a pointer.
Syntax
sizeof(datatype/data)
Advantages of Pointers in C
The following are the main advantages of using pointers in C:
- Pointers are used in the dynamic deallocation and allocation of memory.
- They can be used to pass arguments to functions by reference, allowing the function to modify the values of variables passed to it.
- Pointers allow for effective access to an array or a structure.
- For gaining access to memory regions, pointers are helpful.
- Complex data structures like linked lists, graphs, trees, etc. are created using pointers.
- Pointers shorten both the program's overall length and its execution time.
Disadvantages of Pointers in C
Pointers have the following disadvantages:
- If pointers are given the incorrect value, memory corruption may result.
- It can be challenging to comprehend pointers.
- In C, pointers are mostly to blame for memory leaks.
- In C, pointers move more slowly than variables.
- A segmentation fault might be brought on by uninitialized pointers.
Usage of Pointers in C language
- Dynamic Memory Allocation: Pointers are used to allocate memory dynamically at run time using functions like
malloc()
andcalloc()
. This allows the creation of data structures such as arrays and linked lists of arbitrary size. - Structure: Usage of Pointers in C to manipulate structures, which are collections of variables of different types.
- Passing Arguments to Functions: Pointers can be used to pass arguments to functions by reference, allowing the function to modify the values of variables passed to it.
- Arrays: In C, an array name is a pointer to the first element of the array. The developer can use pointer arithmetic to access elements of an array.
- Pointers to Functions: The developer can define pointers to functions in C, which can be used to pass functions as arguments to other functions, or to create callback functions.
- Strings: In C, strings are arrays of characters. Pointers are commonly used to manipulate strings by accessing individual characters in the string.
Summary
Pointers are a potent tool in C that facilitates effective memory management, dynamic data structures, as well as code optimization. Programmers can deal with complex structures because they can understand their declaration, initialization, & dereferencing. Different pointer types are available in C, each having a particular purpose. Obtaining a "C Programming Certification" can help you master these skills, as pointers have benefits, but they can also cause memory issues, making it essential to learn this skill.
FAQs
Q1. What is a pointer in C and its types?
Q2. What is the syntax of a pointer?
data_type *pointer_variable;