# 指標與記憶體位址

``#include <iostream> using namespace std; int main() {     int var = 10;     cout << "變數var的值：" << var          << endl;     cout << "變數var的記憶體位址：" << &var          << endl;      return 0; }``

type *ptr;

int *iptr;
float *fptr;
char *cptr;

``#include <iostream> using namespace std; int main() {     int var = 10;     int *ptr = &var ;     cout << "變數var的位址：" << &var          << endl;     cout << "指標ptr指向的位址：" << ptr          << endl;      return 0; }``

``#include <iostream> using namespace std; int main() {     int var = 10;     int *ptr = &var;    cout << "指標ptr儲存的值：" << ptr         << endl;     cout << "取出ptr指向的記憶體位置之值：" << *ptr          << endl;     return 0; }``

``#include <iostream> using namespace std; int main() {     int var = 10;     int *ptr = &var ;     cout << "var = " << var          << endl;     cout << "*ptr = " << *ptr          << endl;     *ptr = 20;     cout << "var = " << var          << endl;    cout << "*ptr = " << *ptr          << endl;     return 0; }``

var = 10
*ptr = 10
var = 20
*ptr = 20

int *ptr;
*ptr = 10;

int *iptr = 0;

int *ptr1;
int* ptr2;

int* ptr1, ptr2;

int *ptr1, *ptr2;

void* ptr;

``#include <iostream> using namespace std; int main() {     int var = 10;     void *vptr = &var ;      // 下面這句不可行，void型態指標不可取值     //cout << *vptr << endl;     // 轉型為int型態指標並指定給iptr     int *iptr = reinterpret_cast<int*>(vptr);    cout << *iptr << endl;      return 0; }``

10

int var = 10;
void *vptr = &var ;
// 轉型為int型態指標並指定給iptr
int *iptr = (int*)(vptr);

const int var = 10;
var = 20; // error, assignment of read-only variable `var'
int *ptr = &var; // error,  invalid conversion from `const int*' to `int*'

const int var = 10;
const int *vptr = &var;

*vptr = 20; // error, assignment of read-only location

int x = 10;
int y = 20;
int* const vptr = &x;
vptr = &x;  // error,  assignment of read-only variable `vptr'

``#include <iostream> using namespace std; void foo(const int*);  int main() {     int var = 10;      cout << "var = " << var << endl;      foo(&var);      cout << "var = " << var << endl;      return 0; }void foo(const int* p) {    int* v = const_cast<int*> (p);     *v = 20; }``

*p = 20; // error, assignment of read-only location

int* v = const_cast<int*> (p);
*v = 20;

var = 10
var = 20

void foo(const int* p) {
int* v = (int*) (p);
*v = 20;
}