Difference Between Pointer and Array in C
Pointers and arrays are closely related concepts in C programming, but they are not the same. Understanding their differences is crucial for effective memory management and efficient coding.
What is an Array?
An array is a collection of elements of the same data type stored in contiguous memory locations. Its size is fixed at the time of declaration.
C
// Array example
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
printf("%d", arr[0]);
return 0;
}
What is a Pointer?
A pointer is a variable that stores the memory address of another variable. It allows indirect access and manipulation of data.
C
// Pointer example
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
printf("%d", *ptr);
return 0;
}
Key Differences Between Pointer and Array
- Array is a collection of elements, pointer stores address
- Array size is fixed, pointer can be reassigned
- Array name is constant, pointer is variable
- Arrays use contiguous memory, pointers can point anywhere
- Pointer arithmetic is flexible compared to arrays
Comparison Table
| Feature | Array | Pointer |
|---|---|---|
| Nature | Collection | Address holder |
| Memory | Contiguous | Flexible |
| Size | Fixed | Dynamic (via allocation) |
| Reassignment | Not allowed | Allowed |
| Usage | Store data | Access/manipulate data |
Example Showing Relation
C
// Array and pointer relation
int arr[3] = {1,2,3};
int *ptr = arr;
printf("%d %d", arr[0], *(ptr + 0));
When to Use Array?
- When size is fixed
- For simple data storage
- When direct indexing is needed
- For small datasets
When to Use Pointer?
- Dynamic memory allocation
- Passing large data to functions
- Working with data structures
- Efficient memory handling
Real-World Applications
- Arrays in storing lists of data
- Pointers in linked lists
- Arrays in matrices
- Pointers in dynamic memory management
- Both used in system programming
Common Mistakes to Avoid
- Confusing pointer with array
- Dereferencing NULL pointers
- Out-of-bounds array access
- Memory leaks with pointers
- Incorrect pointer arithmetic
Advanced Concepts
- Pointer to pointer
- Array of pointers
- Pointer arithmetic
- Dynamic arrays
- Function pointers
Practice Exercises
- Create array and pointer relation program
- Implement dynamic array using pointer
- Use pointer arithmetic
- Create array of pointers
- Pass array to function
Conclusion
Pointers and arrays are fundamental in C programming. Arrays provide structured storage, while pointers offer flexibility and control over memory. Understanding both is key to mastering C.
Note: Note: Use arrays for structured data and pointers for flexibility and dynamic memory operations.
Codecrown