Pointer Problem

I am trying to do an exercise from Stroustup's book. The task is to create an array of 7 ints, assign its address to another variable, then print out the array value and the address. My code is below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main ()
{
	int p0[7] = {0, 0, 0, 0, 0, 0, 0};
	int* p1 = &p0;


	for (int i = 0; i < 7; ++i) {
		p0[i] = 2 * (i + 1);
	}

	for (int i = 0; i < 10; ++i) {
		cout <<"Array place " << i << " has value " << p0[i] << ", and its address is " << p1 << ".\n";
	}

        keep_window_open();
        return 0;
}   


My problem is that I get a compile error on line 4 saying that "a value of type int(*)[7] cannot be used to initialize an entity of type int*". I don't understand that message nor how to correct the problem. Thanks in advance for your help.
Last edited on
p0 is of type int[7] (an array). So &p0 gives you a pointer to an array, not a pointer to an int.

Possible solutions are:

1
2
3
4
5
int* p1 = &p0[0];  // get a pointer to the first element

// or...

int* p1 = p0;  // the more common way to do the same thing 
Last edited on
Thank you very much, Disch. It did not occur to me that omitting the subscript would turn my array into an int. As our second suggestion was a previous exercise, i used your first suggestion. It worked fine.

I got the same address for all 7 elements. I suppose that is correct because I set the variable to hold only the address of the first array element.
Topic archived. No new replies allowed.