Arrays and Pointers in C
Programming
Understanding Fundamentals and Applications
Presented by Thejaskumar B R
Introduction
• Arrays: A collection of elements of the same data
type stored in contiguous memory.
• Pointers: Variables that store the memory address
of another variable.
• Purpose:
- Efficient data management and manipulation.
- Foundation for advanced concepts like dynamic
memory allocation.
Arrays in C
• Definition:
dataType arrayName[size];
• Example:
int numbers[5] = {1, 2, 3, 4, 5};
• Key Points:
- Fixed size.
- Indexed starting from 0.
Common Array Operations
1. Initialization:
int arr[3] = {10, 20, 30};
2. Accessing Elements:
printf("%d", arr[0]); // Prints 10
3. Traversing:
for(int i = 0; i < 3; i++) printf("%d", arr[i]);
4. Modifying Elements:
arr[1] = 40;
Pointers in C
- Definition: A pointer is a variable that holds
the address of another variable.
- Syntax:
dataType *pointerName;
- Example:
int num = 10;
int *ptr = # // Pointer stores the address of num
Relationship Between Arrays and Pointers
- Pointer Representation of Arrays:
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d", *(ptr + 1)); // Prints 20
- Key Point: The name of the array represents
the address of its
first element.
Why Use Pointers with Arrays?
1. Dynamic memory access.
2. Simplified data handling.
3. Efficient iteration using pointer arithmetic.
4. Useful in passing arrays to functions.
Passing Arrays to Functions Using Pointers
- Code Example:
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++)
printf("%d ", *(arr + i));
}
int main() {
int numbers[] = {1, 2, 3};
printArray(numbers, 3);
}
Avoiding Common Mistakes
1. Forgetting the `*` or `&` in pointer operations.
2. Exceeding array bounds.
3. Using uninitialized pointers (causes
segmentation faults).
4. Mixing pointer types.
Key Takeaways
- Arrays store multiple elements; pointers store
memory addresses.
- Pointers enhance array manipulation.
- Understand memory layout for debugging
efficiency.
Questions?
Let’s clarify any doubts about arrays and
pointers!
Thank You!