Here is a C code:
#include <stdio.h>
void fun(char**);
int main() {
char*argv[] = {"ab","cd","ef","gh"};
fun(argv);
return 0;
}
void fun(char**p) {
char* t;
t = (p+=sizeof(int))[-1]; //negative index
printf("%s\n",t);
}
I executed this code and got the output as 'gh'. My understanding is that when
int* t = &a
where a is an array then t[-2] will make t to point to *(t-2) and that should be some position prior to the current value of t. But here the output is the next value to the current position of t. Can somebody explain why this is happening?
p+=sizeof(int)
should make p point to argv[2]
. Then how did 'gh' came as output.
EDIT Given that the size of int 2 bytes. It a question from a mock test series. They gave the answer as 'gh'. I too ran the code in my system and got the same answer.
In your system sizeof(int)
turns out to be 4
. Now you added 4
to p
- at this point after addition it points to one past the end of the array. Now you use -1
which makes it point to the last position of the array. And you print it and you get gh
.
"ab" "cd" "ef" "gh"
+----+----+----+----+---
| | | | |
+----+----+----+----+---
^ ^ ^
| | |
p p+3 p+4
And indexing by -1
means p+4-1
or p+3
.
Here also you should check the value of sizeof(int)
before you do this. in case sizeof(int)
turns out to be different then the result would vary, maybe even lead to undefined behavior. (In case if on some system sizeof(int)=8
).
Whatever you said in the end of your question will be valid if sizeof(int)=2
but again p+=sizeof(int)
is not very common way to go about.
In case sizeof(int)=2
then it will give "cd"
as the answer. In case the answer given is something other than "cd"
, then it is wrong.