Decrementing a Pointer for int value

Started by dhilipkumar, Dec 19, 2008, 09:45 PM

Previous topic - Next topic

dhilipkumar

Decrementing a Pointer for int value


#include <iostream>
using namespace std;
const int Length = 3;

int main ()
{
   int testScore[Length] = {4, 7, 1};
   int* intPointer = &testScore[Length - 1];
   int i = Length - 1;
   while (intPointer >= &testScore[0])
   {
      cout << "The address of index " << i
         << " of the array is "<< intPointer << endl;
      cout << "The value at index " << i
         << " of the array is "<< *intPointer << endl;
      intPointer--;
      i--;
   }
   return 0;
}

Using a reference parameter for class type


#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class StringClass {
  char *p;
public:
  StringClass(char *s);
  ~StringClass() {
     delete [] p;
  }
  char *get() {
     return p;
  }
};

StringClass::StringClass(char *s)
{
  int l;

  l = strlen(s)+1;

  p = new char [l];
  if(!p) {
    cout << "Allocation error\n";
    exit(1);
  }

  strcpy(p, s);
}

// Using a reference parameter.
void show(StringClass &x)
{
  char *s;
   
  s = x.get();
  cout << s << endl;
}

int main()
{
  StringClass stringObject1("Hello"), stringObject2("There");

  show(stringObject1);
  show(stringObject2);

  return 0;
}


Assign the public object member address to a pointer



#include <iostream>
using namespace std;

class MyClass {

public:
  int i;
  MyClass(int j) {
     i = j;
  }
};
int main()
{
  MyClass myObject(1);
  int *p;
  p = &myObject.i;                     // get address of myObject.i
  cout << *p;                          // access myObject.i via p
  return 0;
}