ポインタ定数と定数ポインタ
これまで、ポインタ定数と定数ポインタの違いを何度も見ましたが、時間が経つにつれて忘れてしまいました.今度はもう一度勉強して、記録しなければなりません.それぞれ詳しく紹介します.
1、定数ポインタ:定数を指すポインタで、ポインタが指すアドレスの内容は変更できないが、ポインタ自体は可変であることを示す.基本的な定義は次のとおりです.
例は次のとおりです.
正常に動作.定数ポインタが指すオブジェクト(アドレス)が可変であることを示します.次にいくつかの変更を行います.定数ポインタが指すアドレスの内容を変更してみましょう.例は次のとおりです.
プログラムをコンパイルするとき、最後の行が間違っています:cannot convert from'const char[5]'to'const char.定数ポインタがアドレスを指す内容は変更できません.
2、ポインタ定数:ポインタ自体は定数であり、ポインタ自体が可変ではないことを示すが、その指すアドレスの内容は変更可能である.基本的な定義は次のとおりです.
例は次のとおりです.
正常に動作.ポインタ定数が指すアドレスの内容を変更できることを示します.「Hello」から「T」へ.ポインタ定数が指すオブジェクトを変更してみましょう.例は次のとおりです.
プログラムをコンパイルするとき、最後の行が間違っています:you cannot assign to a variable that is const.ポインタ定数が指すアドレスは変更できません.
1、定数ポインタ:定数を指すポインタで、ポインタが指すアドレスの内容は変更できないが、ポインタ自体は可変であることを示す.基本的な定義は次のとおりです.
const char* test = "hello world"; //const *
例は次のとおりです.
#include <iostream>
using namespace std;
void main(){
char * t1 = "Hello";
char * t2 = "World";
const char* test;
test = t1;
cout<<test<<endl;
test = t2;
cout<<test<<endl;
}
正常に動作.定数ポインタが指すオブジェクト(アドレス)が可変であることを示します.次にいくつかの変更を行います.定数ポインタが指すアドレスの内容を変更してみましょう.例は次のとおりです.
#include <iostream>
using namespace std;
void main(){
char * t1 = "Hello";
char * t2 = "World";
const char* test;
test = t1;
cout<<test<<endl;
test = t2;
cout<<test<<endl;
*test = "Test"; // :cannot convert from 'const char [5]' to 'const char'
}
プログラムをコンパイルするとき、最後の行が間違っています:cannot convert from'const char[5]'to'const char.定数ポインタがアドレスを指す内容は変更できません.
2、ポインタ定数:ポインタ自体は定数であり、ポインタ自体が可変ではないことを示すが、その指すアドレスの内容は変更可能である.基本的な定義は次のとおりです.
char* const test = "hello world"; //const *
例は次のとおりです.
#include <iostream>
using namespace std;
void main(){
char * t1 = "Hello";
char * t2 = "World";
char* const test = t1;
cout<<test<<endl;
*test = 'T';
cout<<test<<endl;
}
正常に動作.ポインタ定数が指すアドレスの内容を変更できることを示します.「Hello」から「T」へ.ポインタ定数が指すオブジェクトを変更してみましょう.例は次のとおりです.
#include <iostream>
using namespace std;
void main(){
char * t1 = "Hello";
char * t2 = "World";
char* const test = t1;
cout<<test<<endl;
*test = 'T';
cout<<test<<endl;
test = t2;; // :you cannot assign to a variable that is const
}
プログラムをコンパイルするとき、最後の行が間違っています:you cannot assign to a variable that is const.ポインタ定数が指すアドレスは変更できません.