#include <stdio.h>
int main() {
char *str = "YUKI \0 RENA \0 MIMI";
printf("%s\n%s\n%s" , str , str + 7 , str + 14);
return 0;
}
これを 実行すると
YUKI
RENA
MIMI
となるのはなぜでしょうか。
なぜstr+7でRENAがでて
なぜstr+14でMIMIが出るのか教えてください。
str+7だとAだと思うのですが。
ポインタあ
Re: ポインタあ
コードはBBcodeを有効にした状態でcodeタグで囲み、かつ適切にインデントをしていただけると、見やすくてありがたいです。
(現状のポインタさんのインデントは適切です)
数えてみると、RENAの先頭のRを指していることがわかります。
printfのフォーマット指定%sは、長さの指定が無いので、指定されたポインタからNUL文字に当たるまで連続して文字を書き出します。
よって、printfの%sフォーマットにstr + 7を渡すと、この場合"RENA "が出力されます。
MIMIについても同様に考えればいいです。
(現状のポインタさんのインデントは適切です)
str + 7は、strが指すchar型の要素の7個次の要素を指すポインタになります。ポインタ さんが書きました:なぜstr+7でRENAがでて
なぜstr+14でMIMIが出るのか教えてください。
数えてみると、RENAの先頭のRを指していることがわかります。
0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|13|14|15|16|17|18
--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--
Y |U |K |I | |\0| |R |E |N |A | |\0| |M |I |M |I |\0
(http://port70.net/~nsz/c/c89/c89-draft.html#4.9.6.1)The C89 Draft - 4.9.6.1 The fprintf function さんが書きました: The conversion specifiers and their meanings are
(中略)
s The argument shall be a pointer to an array of character type. Characters from the array are written up to (but not including) a terminating null character; if the precision is specified, no more than that many characters are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character.
よって、printfの%sフォーマットにstr + 7を渡すと、この場合"RENA "が出力されます。
MIMIについても同様に考えればいいです。
逆に、どうしてそう考えたのか教えていただけますか?ポインタ さんが書きました:str+7だとAだと思うのですが。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)
Re: ポインタあ
空白は空白文字であり、文字コードで表すと半角ならASCIIで0x20、全角ならShift_JISで0x81 0x40などです。ポインタ さんが書きました:空文字(空白)と \0 の違いってなんですか?
\0はC言語ではエスケープシーケンスであり、NUL文字(ASCIIコード0x00)と解釈されます。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)
Re: ポインタあ
32は半角空白のASCII文字コードです。ポインタ さんが書きました:32 0となるのですが、どこから32がでてきたんでしょうか。
いいえ、0 (整数)とNULL (C言語では通常「どこも指してない」ポインタ)は別物です。ポインタ さんが書きました:また0はNULLという解釈で大丈夫ですか?
(http://port70.net/~nsz/c/c89/c89-draft.html#3.2.2.3)The C89 Draft さんが書きました:An integral constant expression with the value 0, or such an expression cast to type void * , is called a null pointer constant. If a null pointer constant is assigned to or compared for equality to a pointer, the constant is converted to a pointer of that type. Such a pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
(http://port70.net/~nsz/c/c89/c89-draft.html#4.1.5)The C89 Draft さんが書きました: The macros are
NULL
which expands to an implementation-defined null pointer constant
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)