【初心者お断り】ガチ規格準拠C専用スレ Part133

このエントリーをはてなブックマークに追加
972デフォルトの名無しさん
>>970
C99§6.3.2.3¶5
> An integer may be converted to any pointer type.
> Except as previously specified, the result is implementation defined,
> might not be correctly aligned, might not point to an entity of the referenced type,
> and might be a trap representation.
ただし "previously specified" は整数定数0から空ポインタへの変換に関する規定を指している。

C99§6.3.2.3¶6
> Any pointer type may be converted to an integer type.
> Except as previously specified, the result is implementation-defined.
> If the result cannot be represented in the integer type, the behavior is undefined.
> The result need not be in the range of values of any integer type.
ただし "previously specified" はポインタから_Boolへの変換に関する規定を指している。

一般の整数型とポインタ型の型変換に関して定められているのは以上のみで、
変換可能性については定義されているが、値が同じになるかどうかはわからない。

C99§7.18.1.4で、intptr_tとuintptr_tに関しては、
全ての汎用ポインタをこれらの型に変換したものを汎用ポインタ型に逆変換すると
もとと等しい値になることが保証されている。但し、これらの型の実装はオプショナル。

すなわち、次のコードは期待通りに動く:
| Type* p = malloc( sizeof( Type ) );
| intptr_t a = (intptr_t)(void*)p;
| Type* b = (void*)a;
| assert(p == b);

C89やintptr_t/uintptr_tの存在しないC99処理系では、
一般にポインタ→整数→ポインタのラウンドトリップな変換をする方法はない。

完全に蛇足だが付け加えると、size_tがポインタを格納できる大きさだという保証はない。