0
int main(){
    int a, b;
    char *cp;
    a = 511;
    cp = &a;
    b = *cp;
    *cp = 10;
    printf("%d %d %d", a,b,*cp);
    return 0;
}

The output for the above code is 266 -1 10 I understood how a = 266, this is because the first byte of a is replaced with the binary eqivalent of 10(*cp = 10) that makes a = 0000 0001 0000 1010 . But I am not able to understand why b is -1. In the line b = *cp, *cp in binary is 1111 1111 and this is copied to b, but why the end value is -1?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `cp` is a pointer to a `char`. The `char` type typically can only hold 8 bits. `*cp` is only 8 of the bits used by the `int` variable `a`. When you assign to `*cp` you only modify those specific 8 bits, leaving the remaining unused. Similarly, when you assign from `*cp` you only get those specific 8 bits, not the rest. – Some programmer dude Jun 17 '23 at 16:11
  • given `cp -> -1 (0xff)` the assignment `int b = *cp;` is equal to `int b = -1;` – yvs2014 Jun 17 '23 at 16:28
  • 1
    You shouldn't be using the Turbo C compiler, it has expired long ago. – n. m. could be an AI Jun 17 '23 at 18:08
  • `cp = &a;` is not valid ISO C (9899:1990 or later). – Lundin Jun 19 '23 at 09:16

1 Answers1

1

To understanf the output try this simple demonstration program.

#include <stdio.h>

int main( void )
{
    int a = 511;
    char c = -1;

    printf( "a = %#x, c = %#x\n", a, ( unsigned char )c );
}

Its output is

a = 0x1ff, c = 0xff

It seems the pointer cp assigned like

cp = &a;

points to the less significant byte of the onbject a that contains the value 0xff.

Also it seems that the type char behaves as the type signed char in the compiled program. In this case the value 0xff interpreted as a value of an object of the type char internally represents the value -1. And this value is assigned to the variable b

b = *cp;

So the variable b has the value -1 or in hexadecimal like 0xffffffff (provided that sizeof( int ) is equal to 4) due to the propagating the sign bit according to the integer promotions.

Then this byte is overwritten

*cp = 10;

So now the variable a internally has this value 0x10a (10 in hexadecimal is equal to 0x0a) And in decimal the value is equal to 266.

As a result in this call of printf

printf("%d %d %d", a,b,*cp);

there are outputted a that is equal to 266, b that is equal to -1 and the byte of the variable a pointed to by the pointer cp that is equal to 10.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335