[HELP] learning pointers and need help :)

7. Assume an array is declared as,
int age[6] = {15, 21, 30, 28, 24, 19};
Show the code to display the value of age[5] using pointer notation.

not sure how to point to a specific element in an array and cout its contents.
Here's an example of how to output the first element of an array:

cout << *(arrayName);

and here's how to output the 4th element

cout << *(arrayName+3);

and here's how to output element i, where i is an int and we started counting from zero rather than one, as is the custom.

cout << *(arrayName+i);

The above uses pointer arithmetic and dereferencing.
Last edited on
ok i guess i need to learn the use of (parenthesis) when using pointers. I dont quite understand the use of "i". Where or when would i have an example as such?
1
2
3
4
5
6
// Print out entire contents of array
for (int i = 0; i<sizeOfArray; ++i)
(
  cout << arrayName[i] << " ";
  cout << *(arrayName+i) << " ";
}
+1, got it. where i is the variable you are adding one or whatever to. Thanks, slowly and surely im going to learn this.
I had a real hard time with pointers when I was learning them too. If this makes any more sense I'm happy to help.
1
2
3
4
5
6
7
int age[6] = {15, 21, 30, 28, 24, 19};
    int * pointer_to_age=&age[5];
/* this is the same as
int * pointer_to_age;
pointer_to_age=&age[5]; */
    cout<<*pointer_to_age;
/* same as cout<<age[5];*/


This seems like it would be an easier way to grasp the concept from my perspective.
Topic archived. No new replies allowed.