0
#include<stdio.h>
int main()
{
    unsigned int a=0xabcdef12;
    char *c=(char *)&a;
    int i;
    for(i=0;i<4;i++)
    {

        printf("%x.....%x\n",*c,c);
        c++;
    }
    return 0;
}

O/p:

12.....bfad5bd4
ffffffef.....bfad5bd5
ffffffcd.....bfad5bd6
ffffffab.....bfad5bd7

If you see during first print, it is printing 12 but in all the subsequent prints it is printing correct values but padded with ffffff. Can someone explain this difference??

  • 3
    Sign extension. Try `unsigned char *c=(unsigned char *)&a` – Michael Burr Sep 25 '14 at 06:07
  • Hi Michael... I understand that you want it to typecast it to unsigned char as it is preserving sign by typecasting it to signed int while printing. But can you explain as to why it is not following the case during first print without using unsigned char. – Prashant Gaur Sep 25 '14 at 06:50
  • Because the `char` value `0x12` isn't negative, so there's no sign extension. The `char` values with a bit representation of `0xef`, `0xcd` or `0xab` have negative values. So when they are promoted to `int` in the call to `printf()`, they get sign extended. – Michael Burr Sep 25 '14 at 06:55
  • Michael.....brilliant....I Should have thought about it before asking... – Prashant Gaur Sep 26 '14 at 06:33

1 Answers1

0

You are messing with pointers. Be careful out there. The line

char *bit_longer_name=(char *)&a;

says that "gimme pointer to CHAR type data array, and call it 'bit_longer_name'. The array initializes at variable 'a' address". Now when you do

bit_longer_name++

it actually travels that pointer forward in memory -- goes to next element in a array -- like my_char_array[i] does. The print you have there:

printf("%x.....%x\n",*c,c);

The first part prints the "value of the current array cell i am pointing to", and you are actually passing invalid value for the printf (you should get warning from that!), that causes the compiler to read over from the memory spot pointed by 'c' (-> its working in the first place).

The second part on the other hand is the "address i am pointing to with 'c'", and it travels forward as you can see.

susundberg
  • 650
  • 7
  • 14