簡體   English   中英

在C ++中增加char指針

[英]Incrementing char pointers in C++

為什么這個節目,

char *s, *p, c;

s = "abc";

printf(" Element 1 pointed to by S is '%c'\n", *s);
printf(" Element 2 pointed to by S is '%c'\n", *s+1);
printf(" Element 3 pointed to by S is '%c'\n", *s+2);
printf(" Element 4 pointed to by S is '%c'\n", *s+3);
printf(" Element 5 pointed to by S is '%c'\n", s[3]);
printf(" Element 4 pointed to by S is '%c'\n", *s+4);

給出以下結果?

 Element 1 pointed to by S is 'a'
 Element 2 pointed to by S is 'b'
 Element 3 pointed to by S is 'c'
 Element 4 pointed to by S is 'd'
 Element 5 pointed to by S is ' '
 Element 4 pointed to by S is 'e'

編譯器是如何繼續序列的? 為什么s[3]返回一個空值?

它沒有繼續序列。 你正在做*s+3 ,它首先解引用s給你一個值為'a'char ,然后你添加到那個char值。 將3添加到'a'會給出'd'的值(至少在執行字符集中)。

如果將它們更改為*(s+1) ,依此類推,您將獲得預期的未定義行為。

s[3]訪問字符串的最后一個元素,即空字符。

請注意, *s是一個字符,本質上是一個數字。 添加另一個數字會導致ASCII值更高的字符。 s[3]為空,因為您只將“abc”分別分配給條目0,1,2。 實際上第三個字符是'\\ 0'字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM