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);
}
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 2 of 3.
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".
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)
Suhas said:
1 decade ago
Explanation:
Firstly, t = (p+= sizeof(int))[-1]; is treated as
t=(p=p+(size of int) (-1));
So p="ab" and ab+2-1 becomes cd so it prints "cd" finally.
Thank you..
Firstly, t = (p+= sizeof(int))[-1]; is treated as
t=(p=p+(size of int) (-1));
So p="ab" and ab+2-1 becomes cd so it prints "cd" finally.
Thank you..
Mouneesha said:
1 decade ago
In general size of(int)=4 so in linux it gives p+=4-1=3 i.e index 3 gh
but they have given int is 2 bytes so it gives in windows index 1 i.e cd.
but they have given int is 2 bytes so it gives in windows index 1 i.e cd.
Nagaraj said:
1 decade ago
Can anyone explain how the below statement gets executed
t = (p+= sizeof(int))[-1];
t = (p+= sizeof(int))[-1];
CeParth said:
1 decade ago
OK with Turbo Logic.
But, gcc compiler prints "cd".
Why ?
But, gcc compiler prints "cd".
Why ?
Pra said:
1 decade ago
I think
P[-1] = -p
So, it decrements the value am I correct ?
P[-1] = -p
So, it decrements the value am I correct ?
Amit said:
9 years ago
In an online compiler, it shows gh then how it is cd?
DIPAYAN said:
1 decade ago
But if we remove [-1] it is giving no result. Why?
Mahesh said:
9 years ago
I can't understand the logic. Please explain me.
Dhrn said:
9 years ago
How this program work under linux gcc compiler?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers