Understanding of C pointers, incrementing and dereferencing
I am given a program and am supposed to predict its output.
I have tried to understand the program step by step and write down the value of the variables at each point in the program, but I am not sure what these operations do:
increment(&i);
increment(&a[i]);
#include<stdio.h>
void increment(int *ptr){
++ *ptr;
}
int main(){
int a={5,10},i=0;
increment(a);
increment(&i);
increment(&a[i]);
increment(a+i);
printf("nResult:i=%dn",i);
printf("a[0]=%dn a[1]= %dn", a[0], a[1]);
return 0 ;
}
The solution is:
Result: i = 1
a[0] = 6
a[1] = 12
Could you help me understand how I can derive the solution?
Thank you!
c
add a comment |
I am given a program and am supposed to predict its output.
I have tried to understand the program step by step and write down the value of the variables at each point in the program, but I am not sure what these operations do:
increment(&i);
increment(&a[i]);
#include<stdio.h>
void increment(int *ptr){
++ *ptr;
}
int main(){
int a={5,10},i=0;
increment(a);
increment(&i);
increment(&a[i]);
increment(a+i);
printf("nResult:i=%dn",i);
printf("a[0]=%dn a[1]= %dn", a[0], a[1]);
return 0 ;
}
The solution is:
Result: i = 1
a[0] = 6
a[1] = 12
Could you help me understand how I can derive the solution?
Thank you!
c
1
Which exact step are you unsure about? Do you understand what the addressof operator&
does?
– UnholySheep
Jan 3 at 12:26
1
++ *ptr;
is the same as*ptr += 1;
– pmg
Jan 3 at 12:27
&a[i]
is the same asa + i
is to the value the same asa
.
– Kamil Cuk
Jan 3 at 12:31
Thank you for all your explanations! One thing I am still unsure about is what happens afterincrement(a)
. I thought his would increment a so that it points to a[1], but apparently this is not the case?
– user8558648
Jan 3 at 13:08
@user8558648 the functionincrement()
takes a pointer and increments the pointed value.increment(a)
increments the value stored ata[0]
. Check my answer for step-by-step explanation
– Ki Jéy
Jan 7 at 9:49
add a comment |
I am given a program and am supposed to predict its output.
I have tried to understand the program step by step and write down the value of the variables at each point in the program, but I am not sure what these operations do:
increment(&i);
increment(&a[i]);
#include<stdio.h>
void increment(int *ptr){
++ *ptr;
}
int main(){
int a={5,10},i=0;
increment(a);
increment(&i);
increment(&a[i]);
increment(a+i);
printf("nResult:i=%dn",i);
printf("a[0]=%dn a[1]= %dn", a[0], a[1]);
return 0 ;
}
The solution is:
Result: i = 1
a[0] = 6
a[1] = 12
Could you help me understand how I can derive the solution?
Thank you!
c
I am given a program and am supposed to predict its output.
I have tried to understand the program step by step and write down the value of the variables at each point in the program, but I am not sure what these operations do:
increment(&i);
increment(&a[i]);
#include<stdio.h>
void increment(int *ptr){
++ *ptr;
}
int main(){
int a={5,10},i=0;
increment(a);
increment(&i);
increment(&a[i]);
increment(a+i);
printf("nResult:i=%dn",i);
printf("a[0]=%dn a[1]= %dn", a[0], a[1]);
return 0 ;
}
The solution is:
Result: i = 1
a[0] = 6
a[1] = 12
Could you help me understand how I can derive the solution?
Thank you!
c
c
edited Jan 3 at 13:24
Helena Martins
936219
936219
asked Jan 3 at 12:22
user8558648user8558648
164
164
1
Which exact step are you unsure about? Do you understand what the addressof operator&
does?
– UnholySheep
Jan 3 at 12:26
1
++ *ptr;
is the same as*ptr += 1;
– pmg
Jan 3 at 12:27
&a[i]
is the same asa + i
is to the value the same asa
.
– Kamil Cuk
Jan 3 at 12:31
Thank you for all your explanations! One thing I am still unsure about is what happens afterincrement(a)
. I thought his would increment a so that it points to a[1], but apparently this is not the case?
– user8558648
Jan 3 at 13:08
@user8558648 the functionincrement()
takes a pointer and increments the pointed value.increment(a)
increments the value stored ata[0]
. Check my answer for step-by-step explanation
– Ki Jéy
Jan 7 at 9:49
add a comment |
1
Which exact step are you unsure about? Do you understand what the addressof operator&
does?
– UnholySheep
Jan 3 at 12:26
1
++ *ptr;
is the same as*ptr += 1;
– pmg
Jan 3 at 12:27
&a[i]
is the same asa + i
is to the value the same asa
.
– Kamil Cuk
Jan 3 at 12:31
Thank you for all your explanations! One thing I am still unsure about is what happens afterincrement(a)
. I thought his would increment a so that it points to a[1], but apparently this is not the case?
– user8558648
Jan 3 at 13:08
@user8558648 the functionincrement()
takes a pointer and increments the pointed value.increment(a)
increments the value stored ata[0]
. Check my answer for step-by-step explanation
– Ki Jéy
Jan 7 at 9:49
1
1
Which exact step are you unsure about? Do you understand what the addressof operator
&
does?– UnholySheep
Jan 3 at 12:26
Which exact step are you unsure about? Do you understand what the addressof operator
&
does?– UnholySheep
Jan 3 at 12:26
1
1
++ *ptr;
is the same as *ptr += 1;
– pmg
Jan 3 at 12:27
++ *ptr;
is the same as *ptr += 1;
– pmg
Jan 3 at 12:27
&a[i]
is the same as a + i
is to the value the same as a
.– Kamil Cuk
Jan 3 at 12:31
&a[i]
is the same as a + i
is to the value the same as a
.– Kamil Cuk
Jan 3 at 12:31
Thank you for all your explanations! One thing I am still unsure about is what happens after
increment(a)
. I thought his would increment a so that it points to a[1], but apparently this is not the case?– user8558648
Jan 3 at 13:08
Thank you for all your explanations! One thing I am still unsure about is what happens after
increment(a)
. I thought his would increment a so that it points to a[1], but apparently this is not the case?– user8558648
Jan 3 at 13:08
@user8558648 the function
increment()
takes a pointer and increments the pointed value. increment(a)
increments the value stored at a[0]
. Check my answer for step-by-step explanation– Ki Jéy
Jan 7 at 9:49
@user8558648 the function
increment()
takes a pointer and increments the pointed value. increment(a)
increments the value stored at a[0]
. Check my answer for step-by-step explanation– Ki Jéy
Jan 7 at 9:49
add a comment |
4 Answers
4
active
oldest
votes
but I am not sure what these operations do:
increment(&i);
passes the address of i
variable to your increment function. That function dereferences the pointer and increments the pointed-to value, which is essentially equivalent to i++
.
increment(&a[i])
does the same, but now it passes the address of the i-th element of a
. Since i
was incremented to 1
before, it is equivalent to a[1]++
.
add a comment |
The function increment(int *ptr)
expects a pointer to an int
, i.e. an address.
Since the variable i
is of type int
you have to pass its address by using the address-of operator &
as in: increment(&i)
a[i]
is equal to *(a+i)
- i.e. you access the address of the array element at a+i
and dereference it in order to get the value of that array element at position i
.
Same reason as in the first case, increment
expects a pointer and therefore you have to pass an address as in: increment(&a[i]);
add a comment |
Okay here's a step by step explanation in inline comments. Hope it helps. You may need to scroll horizontally to read the full comment.
#include<stdio.h>
// This function takes a pointer to int and increments the pointed value
void increment(int *ptr){++ *ptr;}
int main(){
int a={5,10},i=0; // It doesn't look so but here, a is a pointer to int
increment(a); // increments the first value pointed by a (a[0]) so now a is [6,10]
increment(&i); // increments i, now i = 1
increment(&a[i]); // increments a[1], now a = [6,11]
increment(a+i); // since i = 1, increments the value right after the one pointed by a so again, a[1], now a = [6,12]
printf("nResult:i=%dn",i);
printf("a[0]=%dn" "a[1]= %dn");
return 0 ;
}
1
It doesn't look so but here,a
is a pointer to int. No,a
is not pointer.a
is an array of integer. Array is not pointer. Array and pointer are different.
– H.S.
Jan 3 at 13:32
Yes @H.S, Arrays declared like thisint a
have a slightly different behaviour than pointers since they are statically allocated but in fact, they are really pointers in the sense that the value thata
holds is an address in memory. Anda[0]
is equivalent to*a
. Check this snippet : gcc.godbolt.org/z/SGCJ1z
– Ki Jéy
Jan 4 at 11:30
@ Ki Jéy a[0] is equivalent to *a doesn't mean that arraya
is a pointer.
– H.S.
Jan 4 at 12:06
the variablea
contains an address. You can read the value stored in that address by dereferencing it with*
.*a
contains the integer you want. Call it whatever you want. For me it's a pointer.
– Ki Jéy
Jan 5 at 18:37
add a comment |
Let's start with some background information.
First, the expression ++i
evaluates to the current value of i
plus 1 - as a side effect, the value stored in i
is incremented. As a standalone expression, it's roughly equivalent to i = i + 1
.
Secondly, except when it is the operand of the sizeof
or unary &
operators, an expression of type "N-element array of T
" (T [N]
) will be converted ("decay") to an expression of type "pointer to T
" (T *
), and the value of the expression will be the address of the first element of the array.
Finally, the expression a[i]
is defined as *(a + i)
- given a starting address a
, offset i
elements (not bytes!) from that address and dereference the result. This means that the expression a + i
is equivalent to the expression &a[i]
.
Let's see how this applies to your code:
In the increment
function, the line
++ *ptr;
adds 1 to the thing that ptr
points to.
When you call increment(a)
, the expression a
has type "2-element array of int
". Since a
is not the operand of the sizeof
or unary &
operators, this expression "decays" to type "pointer to int
" (int *
), and the value of the expression is the address of the first element of a
. IOW, it's exactly the same as if you had written increment(&a[0])
. Therefore, in the increment
function, the following are true:
ptr == &a[0]
*ptr == a[0]
Thus, the expression ++ *ptr
is equivalent to the expression ++ a[0]
. After this call, a[0]
is now 6.
When you call increment(&i)
, ptr
now points to i
:
ptr == &i
*ptr == i
so ++ *ptr
is equivalent to the expression ++ i
, so you're adding 1 to i
.
When you call increment(a[i])
, i
is equal to 1, so this is equivalent to calling increment(a[1])
. After this call, a[1]
is equal to 11.
And finally, increment(a+i)
is equivalent to increment(&a[i])
, which is equivalent to increment(&a[1])
, and after this call a[1]
is equal to 12.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54022229%2funderstanding-of-c-pointers-incrementing-and-dereferencing%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
but I am not sure what these operations do:
increment(&i);
passes the address of i
variable to your increment function. That function dereferences the pointer and increments the pointed-to value, which is essentially equivalent to i++
.
increment(&a[i])
does the same, but now it passes the address of the i-th element of a
. Since i
was incremented to 1
before, it is equivalent to a[1]++
.
add a comment |
but I am not sure what these operations do:
increment(&i);
passes the address of i
variable to your increment function. That function dereferences the pointer and increments the pointed-to value, which is essentially equivalent to i++
.
increment(&a[i])
does the same, but now it passes the address of the i-th element of a
. Since i
was incremented to 1
before, it is equivalent to a[1]++
.
add a comment |
but I am not sure what these operations do:
increment(&i);
passes the address of i
variable to your increment function. That function dereferences the pointer and increments the pointed-to value, which is essentially equivalent to i++
.
increment(&a[i])
does the same, but now it passes the address of the i-th element of a
. Since i
was incremented to 1
before, it is equivalent to a[1]++
.
but I am not sure what these operations do:
increment(&i);
passes the address of i
variable to your increment function. That function dereferences the pointer and increments the pointed-to value, which is essentially equivalent to i++
.
increment(&a[i])
does the same, but now it passes the address of the i-th element of a
. Since i
was incremented to 1
before, it is equivalent to a[1]++
.
answered Jan 3 at 12:29
Bartek BanachewiczBartek Banachewicz
30.8k566109
30.8k566109
add a comment |
add a comment |
The function increment(int *ptr)
expects a pointer to an int
, i.e. an address.
Since the variable i
is of type int
you have to pass its address by using the address-of operator &
as in: increment(&i)
a[i]
is equal to *(a+i)
- i.e. you access the address of the array element at a+i
and dereference it in order to get the value of that array element at position i
.
Same reason as in the first case, increment
expects a pointer and therefore you have to pass an address as in: increment(&a[i]);
add a comment |
The function increment(int *ptr)
expects a pointer to an int
, i.e. an address.
Since the variable i
is of type int
you have to pass its address by using the address-of operator &
as in: increment(&i)
a[i]
is equal to *(a+i)
- i.e. you access the address of the array element at a+i
and dereference it in order to get the value of that array element at position i
.
Same reason as in the first case, increment
expects a pointer and therefore you have to pass an address as in: increment(&a[i]);
add a comment |
The function increment(int *ptr)
expects a pointer to an int
, i.e. an address.
Since the variable i
is of type int
you have to pass its address by using the address-of operator &
as in: increment(&i)
a[i]
is equal to *(a+i)
- i.e. you access the address of the array element at a+i
and dereference it in order to get the value of that array element at position i
.
Same reason as in the first case, increment
expects a pointer and therefore you have to pass an address as in: increment(&a[i]);
The function increment(int *ptr)
expects a pointer to an int
, i.e. an address.
Since the variable i
is of type int
you have to pass its address by using the address-of operator &
as in: increment(&i)
a[i]
is equal to *(a+i)
- i.e. you access the address of the array element at a+i
and dereference it in order to get the value of that array element at position i
.
Same reason as in the first case, increment
expects a pointer and therefore you have to pass an address as in: increment(&a[i]);
answered Jan 3 at 12:31
ElyEly
7,79523154
7,79523154
add a comment |
add a comment |
Okay here's a step by step explanation in inline comments. Hope it helps. You may need to scroll horizontally to read the full comment.
#include<stdio.h>
// This function takes a pointer to int and increments the pointed value
void increment(int *ptr){++ *ptr;}
int main(){
int a={5,10},i=0; // It doesn't look so but here, a is a pointer to int
increment(a); // increments the first value pointed by a (a[0]) so now a is [6,10]
increment(&i); // increments i, now i = 1
increment(&a[i]); // increments a[1], now a = [6,11]
increment(a+i); // since i = 1, increments the value right after the one pointed by a so again, a[1], now a = [6,12]
printf("nResult:i=%dn",i);
printf("a[0]=%dn" "a[1]= %dn");
return 0 ;
}
1
It doesn't look so but here,a
is a pointer to int. No,a
is not pointer.a
is an array of integer. Array is not pointer. Array and pointer are different.
– H.S.
Jan 3 at 13:32
Yes @H.S, Arrays declared like thisint a
have a slightly different behaviour than pointers since they are statically allocated but in fact, they are really pointers in the sense that the value thata
holds is an address in memory. Anda[0]
is equivalent to*a
. Check this snippet : gcc.godbolt.org/z/SGCJ1z
– Ki Jéy
Jan 4 at 11:30
@ Ki Jéy a[0] is equivalent to *a doesn't mean that arraya
is a pointer.
– H.S.
Jan 4 at 12:06
the variablea
contains an address. You can read the value stored in that address by dereferencing it with*
.*a
contains the integer you want. Call it whatever you want. For me it's a pointer.
– Ki Jéy
Jan 5 at 18:37
add a comment |
Okay here's a step by step explanation in inline comments. Hope it helps. You may need to scroll horizontally to read the full comment.
#include<stdio.h>
// This function takes a pointer to int and increments the pointed value
void increment(int *ptr){++ *ptr;}
int main(){
int a={5,10},i=0; // It doesn't look so but here, a is a pointer to int
increment(a); // increments the first value pointed by a (a[0]) so now a is [6,10]
increment(&i); // increments i, now i = 1
increment(&a[i]); // increments a[1], now a = [6,11]
increment(a+i); // since i = 1, increments the value right after the one pointed by a so again, a[1], now a = [6,12]
printf("nResult:i=%dn",i);
printf("a[0]=%dn" "a[1]= %dn");
return 0 ;
}
1
It doesn't look so but here,a
is a pointer to int. No,a
is not pointer.a
is an array of integer. Array is not pointer. Array and pointer are different.
– H.S.
Jan 3 at 13:32
Yes @H.S, Arrays declared like thisint a
have a slightly different behaviour than pointers since they are statically allocated but in fact, they are really pointers in the sense that the value thata
holds is an address in memory. Anda[0]
is equivalent to*a
. Check this snippet : gcc.godbolt.org/z/SGCJ1z
– Ki Jéy
Jan 4 at 11:30
@ Ki Jéy a[0] is equivalent to *a doesn't mean that arraya
is a pointer.
– H.S.
Jan 4 at 12:06
the variablea
contains an address. You can read the value stored in that address by dereferencing it with*
.*a
contains the integer you want. Call it whatever you want. For me it's a pointer.
– Ki Jéy
Jan 5 at 18:37
add a comment |
Okay here's a step by step explanation in inline comments. Hope it helps. You may need to scroll horizontally to read the full comment.
#include<stdio.h>
// This function takes a pointer to int and increments the pointed value
void increment(int *ptr){++ *ptr;}
int main(){
int a={5,10},i=0; // It doesn't look so but here, a is a pointer to int
increment(a); // increments the first value pointed by a (a[0]) so now a is [6,10]
increment(&i); // increments i, now i = 1
increment(&a[i]); // increments a[1], now a = [6,11]
increment(a+i); // since i = 1, increments the value right after the one pointed by a so again, a[1], now a = [6,12]
printf("nResult:i=%dn",i);
printf("a[0]=%dn" "a[1]= %dn");
return 0 ;
}
Okay here's a step by step explanation in inline comments. Hope it helps. You may need to scroll horizontally to read the full comment.
#include<stdio.h>
// This function takes a pointer to int and increments the pointed value
void increment(int *ptr){++ *ptr;}
int main(){
int a={5,10},i=0; // It doesn't look so but here, a is a pointer to int
increment(a); // increments the first value pointed by a (a[0]) so now a is [6,10]
increment(&i); // increments i, now i = 1
increment(&a[i]); // increments a[1], now a = [6,11]
increment(a+i); // since i = 1, increments the value right after the one pointed by a so again, a[1], now a = [6,12]
printf("nResult:i=%dn",i);
printf("a[0]=%dn" "a[1]= %dn");
return 0 ;
}
answered Jan 3 at 13:19
Ki JéyKi Jéy
1,3021024
1,3021024
1
It doesn't look so but here,a
is a pointer to int. No,a
is not pointer.a
is an array of integer. Array is not pointer. Array and pointer are different.
– H.S.
Jan 3 at 13:32
Yes @H.S, Arrays declared like thisint a
have a slightly different behaviour than pointers since they are statically allocated but in fact, they are really pointers in the sense that the value thata
holds is an address in memory. Anda[0]
is equivalent to*a
. Check this snippet : gcc.godbolt.org/z/SGCJ1z
– Ki Jéy
Jan 4 at 11:30
@ Ki Jéy a[0] is equivalent to *a doesn't mean that arraya
is a pointer.
– H.S.
Jan 4 at 12:06
the variablea
contains an address. You can read the value stored in that address by dereferencing it with*
.*a
contains the integer you want. Call it whatever you want. For me it's a pointer.
– Ki Jéy
Jan 5 at 18:37
add a comment |
1
It doesn't look so but here,a
is a pointer to int. No,a
is not pointer.a
is an array of integer. Array is not pointer. Array and pointer are different.
– H.S.
Jan 3 at 13:32
Yes @H.S, Arrays declared like thisint a
have a slightly different behaviour than pointers since they are statically allocated but in fact, they are really pointers in the sense that the value thata
holds is an address in memory. Anda[0]
is equivalent to*a
. Check this snippet : gcc.godbolt.org/z/SGCJ1z
– Ki Jéy
Jan 4 at 11:30
@ Ki Jéy a[0] is equivalent to *a doesn't mean that arraya
is a pointer.
– H.S.
Jan 4 at 12:06
the variablea
contains an address. You can read the value stored in that address by dereferencing it with*
.*a
contains the integer you want. Call it whatever you want. For me it's a pointer.
– Ki Jéy
Jan 5 at 18:37
1
1
It doesn't look so but here,
a
is a pointer to int. No, a
is not pointer. a
is an array of integer. Array is not pointer. Array and pointer are different.– H.S.
Jan 3 at 13:32
It doesn't look so but here,
a
is a pointer to int. No, a
is not pointer. a
is an array of integer. Array is not pointer. Array and pointer are different.– H.S.
Jan 3 at 13:32
Yes @H.S, Arrays declared like this
int a
have a slightly different behaviour than pointers since they are statically allocated but in fact, they are really pointers in the sense that the value that a
holds is an address in memory. And a[0]
is equivalent to *a
. Check this snippet : gcc.godbolt.org/z/SGCJ1z– Ki Jéy
Jan 4 at 11:30
Yes @H.S, Arrays declared like this
int a
have a slightly different behaviour than pointers since they are statically allocated but in fact, they are really pointers in the sense that the value that a
holds is an address in memory. And a[0]
is equivalent to *a
. Check this snippet : gcc.godbolt.org/z/SGCJ1z– Ki Jéy
Jan 4 at 11:30
@ Ki Jéy a[0] is equivalent to *a doesn't mean that array
a
is a pointer.– H.S.
Jan 4 at 12:06
@ Ki Jéy a[0] is equivalent to *a doesn't mean that array
a
is a pointer.– H.S.
Jan 4 at 12:06
the variable
a
contains an address. You can read the value stored in that address by dereferencing it with *
. *a
contains the integer you want. Call it whatever you want. For me it's a pointer.– Ki Jéy
Jan 5 at 18:37
the variable
a
contains an address. You can read the value stored in that address by dereferencing it with *
. *a
contains the integer you want. Call it whatever you want. For me it's a pointer.– Ki Jéy
Jan 5 at 18:37
add a comment |
Let's start with some background information.
First, the expression ++i
evaluates to the current value of i
plus 1 - as a side effect, the value stored in i
is incremented. As a standalone expression, it's roughly equivalent to i = i + 1
.
Secondly, except when it is the operand of the sizeof
or unary &
operators, an expression of type "N-element array of T
" (T [N]
) will be converted ("decay") to an expression of type "pointer to T
" (T *
), and the value of the expression will be the address of the first element of the array.
Finally, the expression a[i]
is defined as *(a + i)
- given a starting address a
, offset i
elements (not bytes!) from that address and dereference the result. This means that the expression a + i
is equivalent to the expression &a[i]
.
Let's see how this applies to your code:
In the increment
function, the line
++ *ptr;
adds 1 to the thing that ptr
points to.
When you call increment(a)
, the expression a
has type "2-element array of int
". Since a
is not the operand of the sizeof
or unary &
operators, this expression "decays" to type "pointer to int
" (int *
), and the value of the expression is the address of the first element of a
. IOW, it's exactly the same as if you had written increment(&a[0])
. Therefore, in the increment
function, the following are true:
ptr == &a[0]
*ptr == a[0]
Thus, the expression ++ *ptr
is equivalent to the expression ++ a[0]
. After this call, a[0]
is now 6.
When you call increment(&i)
, ptr
now points to i
:
ptr == &i
*ptr == i
so ++ *ptr
is equivalent to the expression ++ i
, so you're adding 1 to i
.
When you call increment(a[i])
, i
is equal to 1, so this is equivalent to calling increment(a[1])
. After this call, a[1]
is equal to 11.
And finally, increment(a+i)
is equivalent to increment(&a[i])
, which is equivalent to increment(&a[1])
, and after this call a[1]
is equal to 12.
add a comment |
Let's start with some background information.
First, the expression ++i
evaluates to the current value of i
plus 1 - as a side effect, the value stored in i
is incremented. As a standalone expression, it's roughly equivalent to i = i + 1
.
Secondly, except when it is the operand of the sizeof
or unary &
operators, an expression of type "N-element array of T
" (T [N]
) will be converted ("decay") to an expression of type "pointer to T
" (T *
), and the value of the expression will be the address of the first element of the array.
Finally, the expression a[i]
is defined as *(a + i)
- given a starting address a
, offset i
elements (not bytes!) from that address and dereference the result. This means that the expression a + i
is equivalent to the expression &a[i]
.
Let's see how this applies to your code:
In the increment
function, the line
++ *ptr;
adds 1 to the thing that ptr
points to.
When you call increment(a)
, the expression a
has type "2-element array of int
". Since a
is not the operand of the sizeof
or unary &
operators, this expression "decays" to type "pointer to int
" (int *
), and the value of the expression is the address of the first element of a
. IOW, it's exactly the same as if you had written increment(&a[0])
. Therefore, in the increment
function, the following are true:
ptr == &a[0]
*ptr == a[0]
Thus, the expression ++ *ptr
is equivalent to the expression ++ a[0]
. After this call, a[0]
is now 6.
When you call increment(&i)
, ptr
now points to i
:
ptr == &i
*ptr == i
so ++ *ptr
is equivalent to the expression ++ i
, so you're adding 1 to i
.
When you call increment(a[i])
, i
is equal to 1, so this is equivalent to calling increment(a[1])
. After this call, a[1]
is equal to 11.
And finally, increment(a+i)
is equivalent to increment(&a[i])
, which is equivalent to increment(&a[1])
, and after this call a[1]
is equal to 12.
add a comment |
Let's start with some background information.
First, the expression ++i
evaluates to the current value of i
plus 1 - as a side effect, the value stored in i
is incremented. As a standalone expression, it's roughly equivalent to i = i + 1
.
Secondly, except when it is the operand of the sizeof
or unary &
operators, an expression of type "N-element array of T
" (T [N]
) will be converted ("decay") to an expression of type "pointer to T
" (T *
), and the value of the expression will be the address of the first element of the array.
Finally, the expression a[i]
is defined as *(a + i)
- given a starting address a
, offset i
elements (not bytes!) from that address and dereference the result. This means that the expression a + i
is equivalent to the expression &a[i]
.
Let's see how this applies to your code:
In the increment
function, the line
++ *ptr;
adds 1 to the thing that ptr
points to.
When you call increment(a)
, the expression a
has type "2-element array of int
". Since a
is not the operand of the sizeof
or unary &
operators, this expression "decays" to type "pointer to int
" (int *
), and the value of the expression is the address of the first element of a
. IOW, it's exactly the same as if you had written increment(&a[0])
. Therefore, in the increment
function, the following are true:
ptr == &a[0]
*ptr == a[0]
Thus, the expression ++ *ptr
is equivalent to the expression ++ a[0]
. After this call, a[0]
is now 6.
When you call increment(&i)
, ptr
now points to i
:
ptr == &i
*ptr == i
so ++ *ptr
is equivalent to the expression ++ i
, so you're adding 1 to i
.
When you call increment(a[i])
, i
is equal to 1, so this is equivalent to calling increment(a[1])
. After this call, a[1]
is equal to 11.
And finally, increment(a+i)
is equivalent to increment(&a[i])
, which is equivalent to increment(&a[1])
, and after this call a[1]
is equal to 12.
Let's start with some background information.
First, the expression ++i
evaluates to the current value of i
plus 1 - as a side effect, the value stored in i
is incremented. As a standalone expression, it's roughly equivalent to i = i + 1
.
Secondly, except when it is the operand of the sizeof
or unary &
operators, an expression of type "N-element array of T
" (T [N]
) will be converted ("decay") to an expression of type "pointer to T
" (T *
), and the value of the expression will be the address of the first element of the array.
Finally, the expression a[i]
is defined as *(a + i)
- given a starting address a
, offset i
elements (not bytes!) from that address and dereference the result. This means that the expression a + i
is equivalent to the expression &a[i]
.
Let's see how this applies to your code:
In the increment
function, the line
++ *ptr;
adds 1 to the thing that ptr
points to.
When you call increment(a)
, the expression a
has type "2-element array of int
". Since a
is not the operand of the sizeof
or unary &
operators, this expression "decays" to type "pointer to int
" (int *
), and the value of the expression is the address of the first element of a
. IOW, it's exactly the same as if you had written increment(&a[0])
. Therefore, in the increment
function, the following are true:
ptr == &a[0]
*ptr == a[0]
Thus, the expression ++ *ptr
is equivalent to the expression ++ a[0]
. After this call, a[0]
is now 6.
When you call increment(&i)
, ptr
now points to i
:
ptr == &i
*ptr == i
so ++ *ptr
is equivalent to the expression ++ i
, so you're adding 1 to i
.
When you call increment(a[i])
, i
is equal to 1, so this is equivalent to calling increment(a[1])
. After this call, a[1]
is equal to 11.
And finally, increment(a+i)
is equivalent to increment(&a[i])
, which is equivalent to increment(&a[1])
, and after this call a[1]
is equal to 12.
answered Jan 3 at 14:58
John BodeJohn Bode
83.6k1378151
83.6k1378151
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54022229%2funderstanding-of-c-pointers-incrementing-and-dereferencing%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Which exact step are you unsure about? Do you understand what the addressof operator
&
does?– UnholySheep
Jan 3 at 12:26
1
++ *ptr;
is the same as*ptr += 1;
– pmg
Jan 3 at 12:27
&a[i]
is the same asa + i
is to the value the same asa
.– Kamil Cuk
Jan 3 at 12:31
Thank you for all your explanations! One thing I am still unsure about is what happens after
increment(a)
. I thought his would increment a so that it points to a[1], but apparently this is not the case?– user8558648
Jan 3 at 13:08
@user8558648 the function
increment()
takes a pointer and increments the pointed value.increment(a)
increments the value stored ata[0]
. Check my answer for step-by-step explanation– Ki Jéy
Jan 7 at 9:49