Help Understanding Pointers

Hey, I think I might be missing something here, but it keeps printing random HEX numbers, not the values of the array. Here's my code:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
int main()
{
int intarray[] = { 13, 17, 19, 27, 38, 12 };
int* ptrint;
ptrint = intarray; 
for(int j=0; j<5; j++)
cout << (ptrint++) << endl; 
return 0;
}


Any thoughts?
You need to use the dereference operator ("*") on ptrint in order for it to access the values it's pointing to. Add "*" right before your (ptrint++) statement and it should work.
Also, since you enclose ptrint++ in parentheses it is evaluated before you output the pointed to value (after you include the dereference operator that is.) So the first element in the array won't be passed to cout. Also, your array contains 6 elements. with the test expression in the for loop as j < 5, you will only output elements 1-5 (since when j = 4 it will output element 5 and that will be the last iteration.) Any time you use a for to output each element of an array of size n this way you either use j < n or j <= n-1.

Now, one thing I'm not sure of is how you would make the statement work since *ptrint++ might actually increment the value returned by dereferencing the pointer. To be safe you might want to do something like this (unless someone else can suggest a method that works on one line:

1
2
3
4
5
for (int j = 0; j < 6; ++j)
{
    cout << *ptrint << endl;
    ++ptrint;
}
Last edited on
Actually, ptrint++ will return the value of ptrint BEFORE incrementing it, so what I said is correct. You do need to do j < 6 if you want it to display the last element though.
a pointer points to a space in memory by pointing to the adress sometimes if the space is empty you get the address.

its not quite right but the secret to understanding pointers is to know how they ACTUALY work...and to completley bend your head around the subject so your clear practice using them in arguments for functions
@devonrevenge

.... sometimes if the space is empty you get the address.


Not really, you get the address because you didn't dereference the pointer. You might be confused with accessing a variable that has not been initialised, because that will contain garbage values.
Ah yup, you are right freddy. I forgot the postfix increment returns the original value. So you would be able to write that for sure as *(ptrint++) since that will increment the pointer but return the original address, then dereference it.
Last edited on
Topic archived. No new replies allowed.