I am taking an introductory class in C. We just covered pointers, and our current lab is just to change our code from array notation to pointer notation. I know that in Codeblocks, it takes 4 bytes to store an int variable. So, I assigned a pointer to the front of the array, and based on the lecture from class and from experimentation, I know that by incrementing the pointer, I can change what element of the array that the pointer is pointing to. I figure that incrementing by 4 will allow me to go to the next element of the array.
However, whenever I print the pointer, run pointer =4
, and print the pointer again, it actually changes the value of my pointer by 16. In fact, any increment changes by its multiple of 4. Currently, my code runs fine by instead using pointer
.
My code runs fine, so this shouldn't be an issue, but I wanted to know if anyone could give me more information about why this is the case, and any other information about how Codeblocks stores memory?
CodePudding user response:
Pointer arithmetic is always done in the base unit of the pointer. So if you you have a pointer to int
(i.e. int *
) then doing arithmetic on that pointer will be in the units of int
.
So lets say you have
int arr[] = { 1, 2, 3, 4 };
int *ptr = arr;
then ptr
will point to the first element in the array, arr[0]
.
Now if we increase the pointer ptr
like ptr = ptr 1
(or ptr = 1
or ptr
) then ptr
will point to the second element of the array arr[1]
.
Of you need to visualize it, lets "draw" the array arr
with the pointer and some pointer arithmetic:
----- ----- ----- ----- | 1 | 2 | 3 | 4 | ----- ----- ----- ----- ^ ^ ^ ^ | | | | ptr ptr 1 ptr 2 ptr 3
From this you should start to see a pattern corresponding to array indexing... ptr 1
points to the second element, just like arr[1]
(and ptr[1]
) is the value of the second element.
In fact, all this is the underpinnings of why arr[i]
is exactly equal to *(arr i)
, and the array-to-pointer decay.