Pointer vs array in C
0 200
Both pointers and arrays are fundamental concepts in C, but they serve different purposes and behave differently.
Pointer in C
A pointer is a variable that stores the memory address of another variable.
Example:
// Program for pointer in C #include<stdio.h>int main() { int x = 10; int *ptr; ptr = &x; // Assigning address of x to ptr printf("Value of x: %d\n", x); printf("Address of x: %p\n", &x); printf("Value stored in ptr: %p\n", ptr); printf("Value pointed by ptr: %d\n", *ptr); return 0; }
Output:
Value of x: 10 Address of x: 0x7fff5fbffb6c Value stored in ptr: 0x7fff5fbffb6c Value pointed by ptr: 10
Array in C
An array is a collection of elements of the same type stored in contiguous memory locations.
Example:
// Program for Array in C #include<stdio.h>int main() { int arr[5] = {1, 2, 3, 4, 5}; printf("First element of array: %d\n", arr[0]); printf("Address of first element: %p\n", &arr[0]); printf("Address of array: %p\n", arr); printf("Value pointed by arr: %d\n", *arr); return 0; }
Output:
First element of array: 1 Address of first element: 0x7fff5fbffb70 Address of array: 0x7fff5fbffb70 Value pointed by arr: 1
Differences between Pointer and Array
Feature | Pointer | Array |
Memory Allocation | Points to a single memory location. | Allocates contiguous memory for multiple elements. |
Size | Size depends on architecture (e.g., 4 bytes in 32-bit, 8 bytes in 64-bit). | Size is calculated by multiplying a number of elements by size of each element. |
Accessing Elements | Dereferenced to access the value at the pointed address. | Accessed using indices. |
Arithmetic | Supports pointer arithmetic. | Index-based arithmetic. |
Initialization | Can be initialized with an address or dynamically allocated memory. | Can be initialized with a list of values or dynamically allocated. |
Share:
Comments
Waiting for your comments