C Programming - Functions - Discussion

Discussion Forum : Functions - Find Output of Program (Q.No. 17)
17.
If int is 2 bytes wide.What will be the output of the program?
#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];
    printf("%s\n", t);
}
ab
cd
ef
gh
Answer: Option
Explanation:

Since C is a machine dependent language sizeof(int) may return different values.

The output for the above program will be cd in Windows (Turbo C) and gh in Linux (GCC).

To understand it better, compile and execute the above program in Windows (with Turbo C compiler) and in Linux (GCC compiler).

Discussion:
26 comments Page 3 of 3.

Ashish Bhardwaj said:   8 years ago
@Sahil, it is t= (p+=sizeof(int)) [-1]; and it works like this.

First, sizeof(int) is replaced by 2.
Now, p is of char type so it's incremented by 2bytes during assigning p=p+2. Till this time it's pointing "ef" after this it will point "cd" after executing [-1]. That's all.
(4)

Prince said:   8 years ago
a[-1]=*(a-1),

Now lets consider the code.
here t = (p+= sizeof(int))[-1];,
t=*(x+sizeof(int)-1).
if we consider sizeof(int) is 2 so the line is equals.
*(x+2-1)=*(x+1)=x[1]="cd".
(1)

Saleh Tarek said:   8 years ago
It is very easy:

1-char **p=argv. As argv is an array --> it is a pointer to its 1st element ("ab") --> argv=&("ab").

2- Now: t = (p+= sizeof(int))[-1];

* (p+= sizeof(int) -> p=p+2.
*As p=argv and argv is an array of pointers --> So, size of each element in argv array is 4-bytes--->As a result, +2=+8 bytes. (As sizeof(int=2-bytes)
So, p=&("ef").

Now:
t= &("ef")[-1] is equivalent to &("ef") - 4 (As we mentioned before sizeof("ef") =4-bytes)

So, t=&("cd").

Zdd said:   7 years ago
Thank you @Ashish Bhardwaj.

Sanjana said:   7 years ago
@All.

There must be;

t=(*p+=sizeof(int))[-1];
let's say argv=address of ab.
let's say argv=100.ie ab is stored at address 100.
now argv is sent to a function which takes something which points to char array ie argv
So, p points to argv.
let's say argv has address 200 so p=200.
Now we cannot directly increment p we need to increment *p.
but its written t=(p+=sizeof(int))[-1];
(3)

VIVEK said:   6 years ago
Thanks @Ashish Bhardwaj.
(1)


Post your comments here:

Your comments will be displayed after verification.