0 day streak
c / intermediate
Snippet

Scaling in Pointer Arithmetic

Pointer arithmetic in C is automatically scaled by the size of the data type. Incrementing an integer pointer moves it forward by the number of bytes an 'int' occupies, not just one byte.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30};
int *ptr = arr;
printf("Value: %d\n", *ptr);
ptr++; // Moves by sizeof(int)
printf("Next Value: %d\n", *ptr);
return 0;
}
Breakdown
1
int *ptr = arr;
The pointer is initialized to the address of the first element in the array.
2
ptr++;
Advances the pointer to the next element by adding sizeof(int) bytes to the address.