-1
#include <stdio.h>

int main()
{
int a = -1;
char *p = &a;
printf("%x, %x",*p, *(p+1));
return 0;
}

output is = ffffffff,ffffffff

I know signed integer is represents as ffffffff.

* Expected result should print only one character because it char *

How *(p+1) is ffffffff ?

Is there any difference in

char *p = &a;

and

char *p;
p = &a;
DevesH
  • 486
  • 4
  • 18
Pankaj Suryawanshi
  • 681
  • 1
  • 9
  • 23

3 Answers3

3

An int is more than one byte (how many depends on your system). So int a = -1; sets at least 2 bytes (or more) to FF. Now you create a byte pointer *p and point to the address of the first byte of your a integer. When you use the format x% on a byte, the byte gets padded to an int.

When you try to print the second byte of your int by using *(p+1), the %x will pad the output of the ff to a full int as well.

Update: The process is known as "sign extension" and when a smaller value is used in place of a longer value, the small value is "extended" out such that if the sign is positive, zeros are padded to the left, while if the sign is negative, ones are padded to the left so that the byte FF is seen as an int FFFFFFFF rather than 000000FF. This is considered a "feature" of C so that -1 is still -1.

daShier
  • 2,056
  • 2
  • 8
  • 14
1

To cast the variable to unsigned char you can use the following format:

printf("%hhx, %hhx",*p, *(p+1));

And you can try the output of the following code, maybe you'll get better idea:

#include <stdio.h>

int main()
{
    int a = 0xaf0e3b;
    char *p = &a;
    printf("%hhx, %hhx, %hhx",*(p + 2), *(p+1), *p);
    return 0;
}

out:

af, 0e, 3b

XBlueCode
  • 785
  • 3
  • 18
0

First of all - [Error] cannot convert 'int*' to 'char*' in initialization.

To print character use %c not %x.

%x means that printf will output its value in hexadecimal format.

Ran this code - (Getting space() and comma(,) as output)

int main() {
   int a = -1;
   char *p = (char *)&a;
   printf("%c, %c",*p, *(p+1));
   return 0;
}
DevesH
  • 486
  • 4
  • 18