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 3 of 3.
Anamika said:
1 decade ago
Can anyone explain t = (p+= sizeof(int))[-1]; ?
Nagaraj said:
1 decade ago
Can anyone explain how the below statement gets executed
t = (p+= sizeof(int))[-1];
t = (p+= sizeof(int))[-1];
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 ?
Youssef said:
1 decade ago
Rahul said i don't think it decrement it
p[-1]=p-1
but not
p[-1] = (p=p-1) it dose not affect the result to the var, it just takes the value and decrement it but dose not save it to the variable
p[-1]=p-1
but not
p[-1] = (p=p-1) it dose not affect the result to the var, it just takes the value and decrement it but dose not save it to the variable
Kushnal said:
1 decade ago
thanks bamarthi
Rahul said:
1 decade ago
initally **p contains address of argv[0] element ie "ab".it is then incremented by 2 (size of int given as 2 bytes).now it point to "ef".It is then decremented by -1.so finally points to "cd".so it print value of t as "cd".
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers