-2

I am vastly confused. I'm having a headache. I'm new to C.

#include<stdio.h>

int main()
{
int i = 257;
int *iPtr = &i;    

printf("val 1: %d \t val 2: %d \n\n",*( (char*)iPtr ), *( (char*)iPtr+1) );

int iptr_alias = iPtr;
int and_val = iptr_alias & 255;

printf("Value of iPtr (aka address of i): %d   \n\n", iPtr);
printf("Value at location pointed to by iPtr using %%c: %c \n\n",*iPtr); //gives weird character


int f = 257;
int *fptr = &f;


printf("char starred fptr: %d \t charred 257: %d \n\n",*((char*)fptr), ((char)257) );
// i know the above is obvious. 
system("PAUSE");
}

My questions:

1. Apparently *( (char*) iPtr ) = 257 & 255 = 1 (bitwise and operation). And (char)*iPtr is the same also . But it doesn't print 1 if i use %c modifier. Why?

2. And why *( (char*) iPtr+1 ) = 1 ??

I'm so confused with all this (which i wrote myself to clear confusion, but it worked otherwise..)

((char)257) gives 1 using %d or %o or %x for that matter. %c gives some weird ASCII character

I mean, when i do printf(" %c ", 257) , then i don't get 1, instead, I get a weird ASCII character. Why?

In the actual problem, I was supposed to determine what would be printed as val 1 and val 2.

I maybe overlooking anything stupidly simple, but i'm really feeling confused and tired about this mess. Please help.

4

2 回答 2

1

整数 257 也是十六进制的 0x101。在具有 32 位整数的小端机器上,各个字节将为 0x01 0x01 0x00 0x00。

于 2012-09-25T17:11:48.037 回答
1

请记住,achar只有 8 位,因此可以表示 0 到 255 之间的数字。当您打印257时,它会翻转并变为 1(256将为零)。

至于为什么257(ie 1) 会变成一个奇怪的字符,我把你引向一个ASCII 表

编辑:关于signedunsigned

在这种情况下,您的char类型是unsigned. 如果是这样,signed那么翻转将发生在127(但由于签名/未签名的工作方式,它会翻转到-128并将129翻转到-127)。

于 2012-09-25T16:57:47.607 回答