• edited by
1,704 views
5 5 votes

Consider the following C code fragement -

#include<stdio.h>
int main()
{
    char t[] = "abcdefghij";
    int *p = t;
    p+=2;
    char *c = (char *)p;
    printf("%c", *c);
}

Which of the following is/are correct?

  1. The output of the program in the little-endian system is $\textsf{“ i "}$ (without quotes).
  2. The output of the program in the big-endian system is $\textsf{“ i "}$ (without quotes).
  3. The output of the program in the big-endian system is $\textsf{“ i "}$ (without quotes).
  4. The output of the program in the little-endian system is $\textsf{“ i "}$ (without quotes).

3 Answers

7 7 votes
  • Note that here, string literal is used to assign the array t[]
  • Since p is an int pointer: and we know that pointer arithmetic works based on the type of pointer
  • p+=2 means p=p+2 and p+2 evaluates to p + 2 * sizeof(*p) here sizeof gives 4 bytes (assuming int occupies 4 bytes in the system)
  • hence, pointer p will jump/skip 8 bytes and will land at the address of “i” (initially it was pointing to the 0th element i.e, ‘a’). And later in the code pointer p is typecasted as character pointer and is being saved as character pointer in *c. 
  • And we know that endianness does not apply to arrays. Therefore it doesn't matter if the system uses big endian or the little endian. The output will be the same.
  • Finally, in printf statement *c will fetch the value and %c will print the character ‘i’.
• edited by
1 1 vote
  1. The output of the program in the little-endian system is “i” (without quotes).
  2. The output of the program in the big-endian system is “i” (without quotes).
Answer:
Position:
Show:

Related questions

5 5 votes
1 1 answer
1.1k
1.1k views
GO Classes asked Aug 6, 2022
1,061 views
Consider the following declaration of variable a in C program (row-major order).int a[3][4][5];Which of the following(s) is/are TRUE about pointer arithmetic operations?V...
4 4 votes
1 1 answer
1.4k
1.4k views
GO Classes asked Aug 6, 2022
1,379 views
Let arrays OneD and TwoD are declared as follows as:int OneD[10]; int TwoD[4][5];Which of the following is/are valid syntax to pass OneD and TwoD to some function fun()?A...
2 2 votes
2 2 answers
2.8k
2.8k views
GO Classes asked Aug 6, 2022
2,813 views
In which of the following case(s) character array must end with null char?char c[] = "GATE";char c[] = {'2', '0', '2', '3'};char c[4] = "GATE";char c[16] = "2023";
5 5 votes
2 2 answers
1.7k
1.7k views
GO Classes asked Aug 6, 2022
1,742 views
Consider the following declaration of pointer variable $p.$int (*p)[10][5];If the initial value of $p$ is $1000,$ then what will be the value of $p+1?$It is given that sy...