Const_arith

Constant Pointers and pointer arithmetic

Constant pointers

#include <iostream>

using namespace std;

int main(){

    int a(5);
    int b(6);

    //const pointer
    const int *p; // *p=1 illegal  but p=&a is legal
// can't change value which p points to (p is a movable pointer but it's read only)

    p=&a;
    cout << *p << endl;
    p=&b;
    cout << *p << endl;
    //*p=7; //illegal

    //pointer const
    int* const q(&a);  // q = &b illegal but *q=1 okay
//must initialize q at creation. Can't change location where p points to

    a=9;
    cout << a <<endl;
    *q=8; //okay
    cout << a << " " <<*q <<endl;
    //q=&b; // illegal

    return (0);
}
//easy way to remember if const comes first it's a movable read only pointer
// if it comes after int* then it's a fixed arrow but read/writeable.

//const int* const xp(&a)  is possible

Pointer Arithmetic

#include <iostream>
  2 using namespace std;
  3 // pointer arithmetic and arrays
  4
  5 int main (){
  6     int nums[5]; //an array in C is a pointer.
  7     *nums = 1;  //it points to the first element of the array
  8     cout << nums[0] <<endl; //output is 1
  9     nums[1] = 99; //second element
 10     cout << *(nums+1) << endl; //output 99. pointer arithmetic
 11     cout << &nums[0] << "  " << &nums[1] << endl;
 12
 13     int* p;
 14     p = nums;
 15     *p = 10;
 16
 17     p++; // p now points to nums[1]
 18     *p = 20;
 19     p = &nums[2];  //p now points to nums[2]
 20     *p = 30;
 21     p = nums + 3;  //p now points to nums[3]
 22     *p = 40;
 23     p = nums; // p now points to nums[0]
 24     *(p+4) = 50;
 25     for (int n=0; n<5; n++)
 26     {
 27         cout << nums[n] << ", ";
 28         cout << *(nums + n) <<", ";
 29         cout << *nums + n ; // not the same as above
 30         cout<<endl;
 31     }
 32     return 0;
 33 }

C strings

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;

int main(){

    char a[32] = "Hello";
    const char* b = "Hello";
    char c[] = "Hello";

    a[1] = 'T';
//  b[1] = 'T'; //compile error: cannot modify this cstring (it's read only)
    c[1] = 'T';

    cout<< a << " "<< strlen(a) << " "<< sizeof(a)<<endl;
    cout<< b << " "<< strlen(b) << " "<< sizeof(b)<<endl;
    cout<< c << " "<< strlen(c) << " "<< sizeof(c)<<endl;

    return (0);
}