0
Can we add a single number to an array that is allocated on heap memory ?
Today I started a C++ challenge with someone, and one of the five questions was a bit strange to me : int *data = new int [ 8 ]; for ( int i = 0; i < 8; i++ ) data [ i ] += i + 2; data += 2; What does the last line do ?? I mean data += 2. At first I wanted to google it, but I had no idea what I should search for :( please help me out.
1 Réponse
+ 3
Initially data points to first location of the array that data[0] which is same as *data; (which returns 2)
data += 2 causes the initial pointer advances to 2 pointer location so now data points to the 3rd element( 2nd index location), and now it is data[0] or *data ( now which returns 4)
It is by pointer arithmetic. You can search by "Arrays and pointers arithmetic"