C Aptitude: Endianness, Pointer Arithmetic

C Aptitude 31
In this episode we’ll learn learn more about Endianness, Pointer Arithmetic.

C program is one of most popular programming language which is used for core level of coding across the board. C program is used for operating systems, embedded systems, system engineering, word processors,hard ware drivers, etc.

In this site, we have discussed various type of C programs till date and from now on, we will move further by looking at the C aptitude questions.

In the coming days, we will post C aptitude questions, answers and explanation for interview preparations.

The C aptitude questions and answers for those questions along with explanation for the interview related queries.

We hope that this questions and answers series on C program will help students and freshers who are looking for a job, and also programmers who are looking to update their aptitude on C program.
Some of the illustrated examples will be from the various companies, and IT industry experts.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.


Predict the output or error(s) for the following:

C aptitude 31.1

  
main() {
int i = 258;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}

Answer: 2 1

Explanation: The integer value 257 can be represented in binary as, 00000001 00000001. Remember that the INTEL machines are ‘small-endian’ machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses. The integer value 258 is stored in memory as: 00000001 00000010.

C aptitude 31.2

main() {
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}

Answer:556

Explanation:The integer value 300  in binary notation is: 00000001 00101100. It is  stored in memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresponding to it  is  00000010 00101100 => 556.

C aptitude 31.3

main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
least = ((*ptr)<(least))?(*ptr):(least);
printf("%d", least);
}

Answer: 0
Explanation: After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘