782 views
1 votes
1 votes
#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);
}

can anyone explain this program?

2 Answers

Best answer
2 votes
2 votes
$sizeof(int)$ is compiler dependent

it can be $2$ or $4$ depending on the compiler

if it is $2$, then

 $(p += sizeof(int))[-1]$ can be written as $(p += 2)[-1] $

which can be written as $(p = p+2 - 1)$ which returns address p+1

which is address of $2^{nd}$ element in $argv[]$.

it gives  $cd$

 

if it is $4$, then

 $(p += sizeof(int))[-1]$ can be written as $(p += 4)[-1] $

which can be written as $(p = p+4 - 1)$ which returns address p+3

which is address of $4^{th}$ element in $argv[]$

it will give $gh$
selected by
0 votes
0 votes
**p contains add of "ab"

According to OperatorPrecedence

1)  sizeof(int) = 4

2)  (p +=sozeof(int))  == (p = p +4)

              and p+4 is address of "ij"

3)  (p += sizeof(int))[-1]  mean "gh"

so t = gh

Related questions

0 votes
0 votes
1 answer
1
Debargha Mitra Roy asked Apr 16
76 views
#include <stdio.h int main() { int a[3] = {1, 3, 5, 7, 9, 11}; int *ptr = a[0]; ptr += sizeof(int); printf("%d", *ptr); return 0; }(Assume size of int to be $2$ bytes.)T...
0 votes
0 votes
2 answers
3
Debargha Mitra Roy asked Apr 10
120 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
1 votes
1 votes
1 answer
4
SSR17 asked Feb 29
255 views
#include <stdio.h int main() { int i = -1; int x = (unsigned char)i; printf("%d", x); return 0; }output is 255 , but please explain how