Hello I have a brief question regarding arrays and the [] operator.
I understood that [] "Returns a reference to the element located n elements ahead of the element pointed by the iterator"
In my code, I first declared parray = array;
Then I ran a loop as it is and everything was fine, I get printout of 0, 1, 2, 3, 4.
Why does it still work even when I do (parray + 5)? From what I understand, if I do (parray + 5) and then try to do parray[something] in the loop, it will be accessing not the somethingth slot of the array but the (something + 5) slot. Yet, it still works and I have no array out of bounds or anything.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
using namespace std;
int main (){
int size;
int *parray;
cin >> size;
int array[size];
parray = array;
(parray+5);
for(int i = 0; i < size; i++){
parray[i] = i;
cout << parray[i] << endl;
}
}
|
yakov@kulinich:~/Documents/examples$ ./example8
5
0
1
2
3
4
|
Here is the other version, with (parray + 5) removed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
using namespace std;
int main (){
int size;
int *parray;
cin >> size;
int array[size];
parray = array;
for(int i = 0; i < size; i++){
parray[i] = i;
cout << parray[i] << endl;
}
}
|
yakov@kulinich:~/Documents/examples$ ./example8
5
0
1
2
3
4
|
Can you explain why the first version works? I would have guessed it would be trying to access the 5th, 6th, 7th, 8th 9th slot of an array that only has 0, 1, 2, 3, 4 slots...
Also, why does it compile and allow me to make the size of the array in runtime? I thought that was illegal???