December 15, 2012

more pointerz

Seems like I'll never get the hang of pointers.

In my defense, we've been learning java in class where you never really deal explicitly with pointers.  And java doesn't even call pointers pointers, they have to call it references.  I guess it's a slightly less scary term than pointers, but it's still the same thing.

But now I get to go back to c++ since we're out for break, teaching myself various things again so I don't feel like a bum.

And I just wanted to write a simple program that would traverse the elements of an array and add up all the terms. Simple right?  Except that I'm pointer illiterate and it took me a while.

Anywayz here's what I got:
#include <iostream>
using namespace std;

int main() {
   #define SIZE 3;
   int x[SIZE] = {1, 2, 3);

   int* xptr = x;
   int i = 0, sum = 0;

   cout << "ze array is: ";
   while (i < SIZE) {
      cout << *(xptr + i) << ' ';
      sum += *(xptr + i);
      i++;
   }

   cout << '\n' << x[0] is: " << x[0];
   cout << '\n' << "*x is: " << *x;
   cout << '\n' << *(x + 1) is: " << *(x + 1);
   cout << '\n' << *(x + 2) is: " << *(x + 2);

   return 0;
}

And this is what it outputs:
ze array is: 1 2 3
x[0] is: 1
*x is: 1
*(x + 1) is: 2
*(x + 2) is: 3
sum is: 6

Something I wasn't too happy about is that, for the while loop, I wanted the condition to be while (*(xptr + i) != NULL) but the code wasn't correct for some reason.. It would print out everything I wanted but then print out a bunch of gibberish at the end.

But as always, I learned something new while doing this.  Such as, when you declare an array:
   int x[10]
And you write this:
   *x
Then *x just points to x[0]!  Which is why, in the code above, I was allowed to do shenanigans like
   *(xptr + i)
Since xptr always just points to x, which is really just x[0]!  And (xptr + i) is x[i], and deferencing this just gets you *(xptr + i) = the value at x[i]!

Anyways, yes, easy example, but I'm still recovering from an awful week of finals