in Programming edited by
407 views
3 votes
3 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).
in Programming edited by
407 views

1 comment

 

 

 

Concepts about Little Endian and Big Endian

https://youtu.be/GtzncSKjEeY?list=PLIPZ2_p3RNHgJFMCeS5c13pREPXcoRkaZ

3
3

3 Answers

2 votes
2 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

2 Comments

i think you wanted to write “endianess does not apply to strings array

In array if size of each element is >1B, endianess is applicable. (array won’t be reversed, each element endianess will change)

But, in strings it’s only 1B, hence endianess not applicabe on strings.

1
1
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).
0 votes
0 votes

ENDIANNESS DOES NOT APPLY TO ARRAYS

Answer:

Related questions