- 1
How this code is working please explain the output
#include <stdio.h> void f(char**); int main() { char *argv[] = {"ab", "cd", "ef", "gh", "ij", "kl"}; f(argv); return 0; } void f(char **p){ char *t; t = (p += sizeof(int))[-1]; printf("%s\n", t); }
4 Answers
+ 7
To understand this code, we should first realize that
a[n] is equivalent to *(a+n)
Assuming sizeof(int) returns 4, we can handtrace f(argv) easily.
t = (p += sizeof(int))[-1]
is equivalent to
t = *((p += 4) - 1)
(p += 4) returns a pointer which points to the fifth element in p. Deducting it by 1 causes the pointer to point to the fourth element of p. This value is retrieved and stored in t. The value of t is then printed.
"gh" is printed.
+ 1
#include <stdio.h>
int main(void) {
char x[5] = {1, 2, 3, 4, 5};
char *ptr = (char*)(&x+1);
printf("%d%d\n", *(x+1), *(ptr-1));
return 0;
}
How's this works