Array vs Pointer
Array vs Pointer
com/ 2024-07-10
Arrays in C
An array in C is a collection of elements of the same type, stored in contiguous memory locations. You can
declare an array as follows:
Here, arr is an array of five integers. The elements can be accessed using an index, with arr[0] referring to
the first element, arr[1] to the second, and so on.
Pointers in C
A pointer is a variable that stores the memory address of another variable. You can declare a pointer to an
integer as follows:
int *ptr;
int value = 10;
ptr = &value; // ptr now holds the address of value
Here, ptr is a pointer to an integer, and it holds the address of the variable value.
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
int arr[5] = {1, 2, 3, 4, 5};
1/3
24_2_pointers_arrays.md https://embeddedforall.com/ 2024-07-10
int *ptr = arr; // ptr now points to the first element of arr
// Pointer Arithmetic
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Outputs: 1 2 3 4 5
}
Output:
1
2
3
1 2 3 4 5
1 2 3 4 5
When you use the name of an array in an expression, it is converted to a pointer to the first element of the
array. For example:
Here, ptr points to arr[0]. You can access array elements using this pointer:
Pointer Arithmetic
Pointer arithmetic allows you to traverse an array using a pointer. Consider the following example:
Here, *(ptr + i) accesses the i-th element of the array. This demonstrates how pointers can be used to
iterate over an array.
Pointers are essential for dynamically allocating arrays. The malloc function from the standard library
allocates memory dynamically:
In this example, malloc allocates memory for an array of five integers, and arr acts as a pointer to the first
element of this dynamically allocated array.
3/3