1. What is a Pointer?
A pointer is a variable that stores the memory address of another variable.
Syntax:
data_type *pointer_name;
Example:
x = 10;
int *ptr = &x; // ptr stores the address of x
Here, ptr
is a pointer to an integer variable x
, storing its memory address.
An array is a collection of elements of the same data type, stored in contiguous memory locations.
Example:
int arr[5] = {10, 20, 30, 40, 50};
Here, arr
is an integer array of size 5.
arr
gives the memory address of arr[0]
.#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer to array
printf("First element: %d\n", *ptr); // 10
printf("Second element: %d\n", *(ptr+1)); // 20
printf("Third element: %d\n", *(ptr+2)); // 30
return 0;
}
Explanation:
ptr
stores the address of arr[0]
*(ptr + 1)
fetches the second element arr[1]
*(ptr + 2)
fetches the third element arr[2]
Pointers support arithmetic operations like:
ptr++
) → Moves to the next array element.ptr--
) → Moves to the previous array element.ptr + n
) → Moves n
elements ahead.ptr - n
) → Moves n
elements back.#include <stdio.h>
int main() {
int arr[] = {5, 10, 15, 20, 25};
int *ptr = arr; // Points to arr[0]
for(int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(ptr + i));
}
return 0;
}
Output:
yamlCopyEditElement 0: 5
Element 1: 10
Element 2: 15
Element 3: 20
Element 4: 25
Since arrays are passed by reference, we can use pointers to manipulate arrays inside functions.
#include <stdio.h>
void modifyArray(int *arr, int size) {
for(int i = 0; i < size; i++) {
arr[i] *= 2; // Doubling each element
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
modifyArray(arr, size);
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
2 4 6 8 10
Since we passed a pointer to the array, modifications inside modifyArray()
reflect in main()
.
Using malloc
, we can dynamically allocate memory for an array.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n = 5;
// Allocating memory for 5 integers
arr = (int*)malloc(n * sizeof(int));
// Assigning values
for(int i = 0; i < n; i++) {
arr[i] = i + 1;
}
// Printing values
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free allocated memory
free(arr);
return 0;
}
Output:
1 2 3 4 5
Here, we dynamically allocate memory for an array using malloc
and free it using free()
.
Pointers and arrays are fundamental concepts in C programming that are deeply interconnected. Understanding their relationship allows for efficient memory management and optimized code execution.