edited by
1,028 views
4 votes
4 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).
edited by

3 Answers

4 votes
4 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
0 votes
0 votes
  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:

Related questions

1 votes
1 votes
2 answers
2
GO Classes asked Aug 6, 2022
1,117 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";