0
Changing element values in an array
using namespace std; #include <iostream> int main() { int*data = new int[8]; for(int i=0; i<8; i++) data[i] = i+2; // data[8]={2,3,4,5,6,7,8,9} data += 2; // adds 2 to each of the above elements? cout << data[0] << data[1] << data[2] << data[3] << data[4] << data[5] << data[6] << data[7] ; } // outputs 45678900 Why does data[6] and data [7] output 0 instead of 10 and 11 respectively?
3 Respostas
+ 3
It would be much more clear if you consider *data* as a pointer pointing at the first element of the array and data[n] as *(data+n).
so just like swim said when you increment data pointer in line 7 of your program ( data +=2 ) you are making the pointer point to the 3rd element of the array instead of first. so now if you try to access data[0] which is *(data+0) then you will land on third value of the array only.