Gozo
Gozo

Reputation: 13

Understanding the output of this code in C language

#include<stdio.h> 

void main()

{
    int a,b;
    char *cp;

    a=511;

    cp=&a;

    b=*cp;

    *cp=10;

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

It is giving out 266 -1 10 in gcc with a warning : assignment to 'char *' from incompatible pointer type 'int *' [-Wincompatible-pointer-types] cp=&a; I know cp is a char pointer so it is giving me a warning.

I am not able to understand output for a and b;

Upvotes: 1

Views: 184

Answers (2)

Sourabh Choure
Sourabh Choure

Reputation: 733

    int a,b;
    char *cp;

    a=511;

    cp=&a;

The range of the char type variable is from [-128 to 127] and of int is [-32,768 to 32,767] or [-2,147,483,648 to 2,147,483,647].

So, when you store a larger data type that requires more bits into a smaller data type which requires fewer bits, then it will lead to narrow conversion, more properly known as Unsafe Type Conversion.

Try to assign value to a which is in the range of the char i.e. [-127 to 128] then you will get a predictable output, otherwise, it can be Undefined Behaviour.

Upvotes: 0

carveone
carveone

Reputation: 909

The answers you get will depend on how your particular processor is storing an integer. On a 32 bit "little endian" machine, it will store the number 511 (1FF in hexadecimal), somewhere in memory as:

FF 01 00 00

from lowest memory location (FF) to highest(00). You then take the "address of a" and say "make this a character pointer" and assign it to "cp".

Except you miss out the "make this" part and gcc does this for you - this is why you get the warning. To remove the warning you must tell gcc: "yes, I want to do this". You do that by explicitly taking the integer pointer and making into a character pointer:

cp = (char *)&a;

OK. So now you have a character pointer pointing to the first address where you have an FF stored. You dereference this (with *cp) to get a signed char. The value of this is -1 which you put in b.

You then change the FF to 0A (10 in decimal). The memory now looks like this:

0A 01 00 00

Upvotes: 2

Related Questions