2016-04-07 8 views
-5
char *s; 
char buf [] = "This is a test"; 

s = strchr (buf, 't'); 

if (s != NULL) 
    printf ("found a 't' at %s\n", s); 
printf("%c\n",*s); 
printf("%c\n",*s++); 
printf("%c\n",*s++); 
printf("%c\n",*s++); 
printf("%c\n",*s++); 

このコード出力:私の見解ではなぜ* sと* s ++が同じ値を持つのか?

found a 't' at test 
t 
t 
e 
s 
t 
Program ended with exit code: 0 

は、* sがtであるべきで、* S ++ eでなければなりません。しかし、なぜ彼らはこのコードで同じ価値を持っていますか?式*s++

+5

「あなたの意見」は何かに基づいていますか? –

+1

ポストインクリメント手段は、インクリメントしてインクリメントします。 Try *(++ s) – sircodesalot

+0

sは文字列sの先頭アドレスを意味するので、* sはアドレスに格納されている値でなければなりません。 s ++は文字列sの先頭アドレスから次の位置になければなりません。 –

答えて

5

++ポスト -incrementオペレータあります。 、

sの値が続いて s
  • その後sの古い値が参照解除され
  • だから、インクリメントされ

  • を得ている

    • :それは次のようにして次、たまたま意味します
      printf("%c\n",*s);  // Prints the character at s 
      printf("%c\n",*s++); // Prints the character at s 
               // ***and then*** increments it 
      

      両者は同じ文字を印刷します。


      あなたは、それは、単にsにポストインクリメントすることなく、第1 printfを削除すべきだと思うようにあなたの例のコードは動作するようにしたい場合:

           // s points to the 't' 
      
      printf("%c\n",*s++); // Prints 't'. Afterward, s points to the 'e' 
      printf("%c\n",*s++); // Prints 'e'. Afterward, s points to the 's' 
      printf("%c\n",*s++); // Prints 's'. Afterward, s points to the 't' 
      printf("%c\n",*s++); // Prints 't'. Afterward, s points to the NUL terminator 
      
  • 1
    printf("%c\n",*s++); 
    

    (多かれ少なかれです1に相当)

    printf("%c\n",*s); 
    s++; 
    

    T彼はなぜ't'が2回印刷されているのを見ているのですか?

    i++は、の値の値をと評価し、副作用として変数をインクリメントします。


    1.多かれ少なかれs*s後に更新されますので、評価されていますが、printf前に実際に呼び出されます。 ++の副作用が適用された正確なことは、次のシーケンスポイントの前に起こります。この場合、すべての関数引数が評価され、関数が呼び出される前にシーケンスポイントが発生します。

    +0

    シーケンスポイントを表示するのにプラスです。 –

    関連する問題