The Gateway to Computer Science Excellence
+1 vote
122 views

Can you see why the output of the following code is 256?

main ()
    {
        int a=0x1ff;
        char *careful= &a;
        *careful = 0;
        printf("%d", a);
    }
in Algorithms by Junior (941 points) | 122 views
0
It is 2's complement representation of 0
0
That's clear but still there is something more to it :p.
0
wait. 0 in 2's complement is represented by all bits 0.

2 Answers

+1 vote

Thanks.

by Junior (941 points)
0 votes
char is a signed type. It takes value from -128 to 127

Now, u r taking a value which is in int and pointing by a character pointer.Now u make the value pointed by char pointer is 0. Now, again trying to print that value to print in integer, which will be out of range. So, it gives an overflow and that makes 9th bit as 1.
by Veteran (119k points)
0
Partially correct.

Hint 1:Actually char points to 1 byte while integer stores value in 4 byte.

Hint 2: It can also act as a check to whether your machine is big-endian or little endian.

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
50,737 questions
57,324 answers
198,405 comments
105,169 users