I have this piece of program and there are some parts that I don't understand...
#include <stdio.h>
void increment( int *ptr) {++*ptr; }
int main(){
int a[] = { 5, 10 }, i = 0; // We have: vector a=[5,10] | i=0
increment(a); //This is the same as increment(&a) isn't it?
//So we have: a=[6,10] | i=0
increment(&i); // We increment i so: a=[6,10] | i=1
increment(&a[i]); //We increment the element at the position a[1]: a=[6,11] | i=1
increment(a+i); //OMG! What does it mean? a is an array isn't it? Then how can we
//make "a+1"? and how is this an address?
printf("\nResult: i= %d\n", i);
printf( "a[0] = %d\n" "a[1] = %d\n", a[0], a[1]);
return 0;
}
The printf
s return:
i=1
a[0]=6
a[1]=12
How can this be explained?
When you pass an array to a function, the array decays to a pointer to the first element. So in the function, doing eg *ptr
is dereferencing the first element in the array.
Also, because arrays decays to pointers, doing eg a[i]
is equal to *(a + i)
.
Unrelated side-note: Because of the commutative of addition, the expression *(a + i)
can be written as *(i + a)
which leads to i[a]
actually being a valid expression.
Arrays and pointer arithmetic are the same in C. If you've not come across pointer arithmetic here's a tutorial on it: C Pointer Arithemtic
In essence:
a[3]
is the same as
*(a + 3)
Where a
is a pointer.
When we give the name of array in the function call, the address of the arrya's first element is passed
ie; increment(a); is same as increment(&a[0]);
So while giving
incrementa(a+i);
since i and array a[] are both integers effectively that becomes
incrementa ( base address of array a (ie; &a[0]) + value of i )
i just acts as the offset to that array element
That it becomes the address of the second element which is &a[1]
so the 11 is modified to 12 while incrementing the value by the function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.