定数ポインタとポインタ定数
「定数ポインタ」とは何かを説明せず、「ポインタ定数」とは何かを説明せず、コードに直接接続します.
ポインタ定数:
ポインタ定数はここでint*const ptrであり、ptrは定数では変更できず、ptrが指す変数も変更できないが、ptrが指す変数の値をptrで変更することができる.
「ポインタ定数」が指すアドレスは定数であり、アドレス上のデータは変化可能である.
定数ポインタ:
ここでconst int*ptrは、ptrが指す変数の値がptrにとって定数であることを示し、ptrで指す変数の値を変更することはできないが、他の方法でその指す変数の値を変更することができる.
ptr自体は定数ではなく、他の変数を指すことができる.「定数ポインタ」は、その名の通り、定数を指すポインタであり、指すアドレス上のデータはポインタにとって定数である.
int*const ptrとconst int*ptrの違いはconstと誰の前に置くか、constが誰の前に置くか、誰が定数です.
ポインタ定数:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int num1 = 1;
int num2 = 2;
int* const ptr = &num1;
cout<<*ptr<<endl;
// ptr
//error C3892: “ptr”:
//ptr = &num2;
//cout<<*ptr<<endl;
// ptr
//ok output=3
*ptr = 3;
cout<<*ptr<<endl;
// ptr
//ok output=4
num1 = 4;
cout<<*ptr<<endl;
return 0;
}
ポインタ定数はここでint*const ptrであり、ptrは定数では変更できず、ptrが指す変数も変更できないが、ptrが指す変数の値をptrで変更することができる.
「ポインタ定数」が指すアドレスは定数であり、アドレス上のデータは変化可能である.
定数ポインタ:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int num1 = 1;
int num2 = 2;
const int* ptr = &num1;
cout<<*ptr<<endl;
// ptr
//ok, output=2
ptr = &num2;
cout<<*ptr<<endl;
// ptr
//error C3892: “ptr”:
//*ptr = 3;
//cout<<*ptr<<endl;
// ptr
//ok, output=4
num1 = 4;
cout<<*ptr<<endl;
return 0;
}
ここでconst int*ptrは、ptrが指す変数の値がptrにとって定数であることを示し、ptrで指す変数の値を変更することはできないが、他の方法でその指す変数の値を変更することができる.
ptr自体は定数ではなく、他の変数を指すことができる.「定数ポインタ」は、その名の通り、定数を指すポインタであり、指すアドレス上のデータはポインタにとって定数である.
int*const ptrとconst int*ptrの違いはconstと誰の前に置くか、constが誰の前に置くか、誰が定数です.