2

私はたまたまこの質問を見たウェブサイトで C の模擬試験を受けていました。My Doubt はコメントで説明されているので、読んでください。

#include<stdio.h>

int main()
{
    int arr[3] = {2, 3, 4};  // its assumed to be stored in little-endian i.e;
                             // 2 = 00000010 00000000 00000000 00000000
                             // 3 = 00000011 00000000 00000000 00000000
                             // 4 = 00000100 00000000 00000000 00000000   

    char *p;

    p = arr;

    p = (char*)((int*)(p));  

    printf("%d ", *p);   

    p = (int*)(p+1);       // This casting is expected to convert char pointer p 
                           // to an int pointer , thus value at p ,now is assumed 
                           // to be equal to 00000000 00000000 00000000 00000011 
                           // but, the output was : 0  . As ,per my assumption it
                           // should be : 2^24+2^25 = 50331648 ,Please Clarify 
                           // if my assumption is Wrong and explain Why?

    printf("%d\n", *p);

    return 0;
 }
4

3 に答える 3

2

にキャストpバックするint*と、int値は次のようになります。

00000000 00000000 00000000 00000011

最後のバイトは、2 番目の配列要素の最初のバイトです。を実行p+1すると、最初の要素の最下位バイトがスキップされます。

pこれは char ポインタのままなので、 anint*を割り当てても型は変わらないことに注意してください。

printfで char を実行するとp+1、2 番目のバイトの値である 0 が出力されます。

于 2013-04-12T05:29:06.700 に答える
1

覚えておいpて、まだcharポインターです。したがって、そこから値を*p取得します。char次に、可変引数関数 ( など) に引数として渡されるとchar、値は に昇格されます。intprintf

于 2013-04-12T05:32:44.680 に答える
1
p = (char*)((int*)(p));
// till now the pointer p is type casted to store the variable of type character.

printf("%d, ", *p); // %d means integer value so value at first address i.e. 2 will be printed.

p = (int*)(p+1); // here p is still of type character as type casted in step 1 so p(i.e address) and plus 1 will increase only by one byte so  

整数に 2 バイトのストレージが必要であると仮定すると、整数配列は次のようにメモリに格納されます。

value 2 3 4
address 00000010 00000000 00000011 00000000 00000100 00000000 
pointer p+1 

そのためp+1、初期化中に 2、3、4 が整数型 (2 バイト) の変数に格納されたため、埋められていない場所を指します。

p+1指し00000000ます。

(int*)p+1 // p+1 is type casted again to integer

printf("%d", *p); // this will print 0 as output as by default integer contains 0 as value.

于 2013-04-12T05:37:34.427 に答える