The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
0 votes
60 views

What will be the output of the below code? the answer given is E)0 but I am not getting it.
 

#include <stdio.h>
void fun(short int *a,char *b)
{
    b += 2;
    short int *p = (short int*)b;
    *p = *a;
}


int main()
{
    void (*fptr)(short int *,char *)
    short int a = 101;
    char arr[] = {'a','b','c','d'};
    fptr = fun;
    (*fptr)(&a,arr);
    printf("%d", arr[3]);

    return 0;
}


$A)$ Compilation error.

$B) 100$

$C)$ Garbage Value

$D)$ Segmentation Fault.

$E) 0$

asked in Programming by (39 points)
edited by | 60 views

1 Answer

+1 vote
Best answer

go through these links before reading answer if these concepts are not clear

https://stackoverflow.com/questions/12279060/what-is-the-difference-between-short-int-and-int-in-c

https://www.geeksforgeeks.org/little-and-big-endian-mystery/

 

A[0](1000+0) A[1](1000+1) A[2](1000+2) A[3](1000+3)
a b c d

short int *p = (short int*)b;

what this line does is assigns address 1002 in "p" in such a way that it will take 2 bytes 1002 and 1003(since it takes 2 bytes)

Now, when we assign 101 to it because of little-endian format, the higher order byte having 0 will be placed in right (A[3]) and lower order byte having value 101 at A[2], What you can do to test this is run the same program with 300 O/P would be 1 because higher order byte has 1(requires 256) 

answered by Active (1.9k points)
selected by
0

Thanks @Anuj Mishra but, is it syntactically correct to assign fun to fptr?

0

Yes it is correct (function name itself is like an array name - so you can remove & and it still works - definitely go through this for reading and examples-http://www.cs.cmu.edu/~guna/15-123S11/Lectures/Lecture14.pdf

Also if  times, search wiki for function pointer - there you'll get a good example and some important usage too

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
49,540 questions
54,099 answers
187,269 comments
71,006 users