ホームページ  >  記事  >  バックエンド開発  >  C の const char*p、char*const p、および const char*const p の違い

C の const char*p、char*const p、および const char*const p の違い

PHPz
PHPz転載
2023-09-08 19:25:03602ブラウズ

C中const char*p、char*const p和const char*const p之间的差异

ポインタ

C プログラミング言語では、*p はポインタに格納された値を表し、p は値のアドレスを表します。ポインタ。

const char* および char const* は、ポインタが定数文字を指すことができ、ポインタが指す文字の値は変更できないことを示します。ただし、ポインターは定数ではなく、別の定数文字を指すことができるため、その値を変更することができます。

char* const は、ポインタが文字を指すことができ、ポインタが指す文字の値を変更できることを意味します。ただし、ポインタは定数になっており、別の文字を指すことができないため、その値を変更することはできません。

const char* const は、ポインタが定数文字を指すことができ、ポインタが指す文字の値は変更できないことを意味します。また、ポインタは定数になっており、別の定数文字を指すことができないため、その値を変更することもできません。

名前付け構文の原則は右から左です。

// constant pointer to constant char
const char * const
// constant pointer to char
char * const
// pointer to constant char
const char *

例 (C)

エラーのあるコードのコメントを解除し、エラーを表示します。

リアルタイム デモンストレーション

#include <stdio.h>
int main() {
   //Example: char const*
   //Note: char const* is same as const char*
   const char p = &#39;A&#39;;
   // q is a pointer to const char
   char const* q = &p;
   //Invalid asssignment
   // value of p cannot be changed
   // error: assignment of read-only location &#39;*q&#39;
   //*q = &#39;B&#39;;
   const char r = &#39;C&#39;;
   //q can point to another const char
   q = &r;
   printf("%c</p><p>", *q);
   //Example: char* const
   char u = &#39;D&#39;;
   char * const t = &u;
   //You can change the value
   *t = &#39;E&#39;;
   printf("%c", *t);
   // Invalid asssignment
   // t cannot be changed
   // error: assignment of read-only variable &#39;t&#39;
   //t = &r;
   //Example: char const* const
   char const* const s = &p;
   // Invalid asssignment
   // value of s cannot be changed
   // error: assignment of read-only location &#39;*s&#39;
   // *s = &#39;D&#39;;
   // Invalid asssignment
   // s cannot be changed
   // error: assignment of read-only variable &#39;s&#39;
   // s = &r;
   return 0;
}

出力

C
E

以上がC の const char*p、char*const p、および const char*const p の違いの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。