Labs ICT
Pro Login

Pointers & Arrays

Arrays and pointers are best friends in C — so close that an array name is really just a pointer to its first element. Once you see that connection, a whole lot of things click into place.

Array Name as Pointer

When you declare an array, its name acts like a constant pointer to the first element. That means arr and &arr[0] are the same thing.


#include 
int main() {
  int arr[] = {10, 20, 30};
  printf("arr = %p\n", arr);
  printf("&arr[0] = %p\n", &arr[0]);
  printf("*arr = %d\n", *arr);
  return 0;
}
    
Try it Yourself →

Pointer Arithmetic

Adding 1 to a pointer doesn't add 1 byte — it moves to the next element of whatever type the pointer points to. So for an int pointer (4 bytes), ptr + 1 jumps 4 bytes forward.


#include 
int main() {
  int arr[] = {10, 20, 30, 40};
  int *ptr = arr;
  for (int i = 0; i < 4; i++) {
    printf("arr[%d] = %d\n", i, *(ptr + i));
  }
  return 0;
}
    
Try it Yourself →

Passing Arrays to Functions

When you pass an array to a function, what actually gets passed is a pointer. That's why the function can modify the original array — it's working directly with the memory, not a copy.


#include 
void doubleValues(int *arr, int size) {
  for (int i = 0; i < size; i++) {
    arr[i] *= 2;
  }
}
int main() {
  int numbers[] = {1, 2, 3, 4};
  int count = 4;
  doubleValues(numbers, count);
  for (int i = 0; i < count; i++) {
    printf("%d ", numbers[i]);
  }
  printf("\n");
  return 0;
}
    
Try it Yourself →

Array Indexing vs Pointer Arithmetic

arr[i] is just syntactic sugar for *(arr + i). The compiler treats them identically. Use whichever reads better — both are equally fast.


#include 
int main() {
  int arr[] = {5, 10, 15};
  printf("arr[1] = %d\n", arr[1]);
  printf("*(arr + 1) = %d\n", *(arr + 1));
  printf("1[arr] = %d\n", 1[arr]);
  return 0;
}
    
Try it Yourself →