question about pointers

I have to answer some questions that does not require me to write a program. I have some of it done, but I am not sure if it is correct and other parts have me stumped.



For each of the following, write C++ statements that perform the specified task. Assume
that unsigned integers are stored in two bytes and that the starting address of the array is at location 1002500 in memory.
a) Declare an array of type int called values with five elements, and initialize
the elements to the even integers from 2 to 10. Assume that the symbolic constant SIZE
has been defined as 5.
b) Declare a pointer vPtr that points to an integer variable.
c) Use a for statement to print the elements of array values using array subscript notation.
d) Write a statement that assign the starting address of array values to pointer
variable vPtr.
e) Use a for statement to print the elements of array values using pointer/offset notation.
f) What address is referenced by vPtr + 3? What value is stored at that location?
g) Assuming that vPtr points to values[ 4 ], what address is referenced by vPtr -= 4?
What value is stored at that location?


I think I have most of part A
int values[5]{2, 4, 6, 8, 10};

but the words "Assume that the symbolic constant SIZE has been defined as 5." is confusing me.


This is what I have for part b, I do not know if this is correct.

1
2
int *vPtr;
vPtr=values[5];


Part c

1
2
3
4
for (i = 0; i < 5; i++)
	{
		cout << values[i] << endl;
	}


The code seems to work but the words
using array subscript notation
is not something I have seen before.

I am lost on the rest of the questions, any help or links to related material would be really helpful.
An array IS a pointer. When it says "array subscript notation" it just means array[i]. The '[i]' is the subscript.

To assign the pointer to point to another vairable, you can do this:
1
2
3
int *vPtr;
int number = 5;
vPtr = &number;


vPtr = values[5] won't work. You're trying to put an integer into a pointer of type int (pointers hold memory addresses, not integers). Think about how you can retrieve the memory location of a variable (hint, look at the code above).
Also, it should be values[4] if you want to access the 5th element in the array.

Pointer arithmetic is great. If you do "vPtr + 1" it will go to the next element, just like if you did vPtr[i + 1] (if vPtr was an array). Keep that in mind for the last 3 questions.
Last edited on
Thanks for clearing up my answers and the hints for the next questions.
Topic archived. No new replies allowed.