pointers - Array address in c++ -
i have code :
int n; cin >> n; int array[n];  (int = 0; < n; ++i) {     cin >> array[i];   }  int tmp[n - 1]; tmp[0] = 1;   with input : 1 10  found value of array[0] changed , instead of 10 has same tmp[0]. 
then realized input length of tmp[] became zero. print address of array[] , tmp[] with:
printf("%d\n %d\n", array, tmp);   and found had same address.
i want figure out happen if array has length of 0; tried this:
int array[1]; array[0] = 10;  int tmp[0]; tmp[0] = 1;   address:
array[]: 1363909056 tmp[]  : 1363909052   it looks previous code (except input part). tmp[0] , array[0] has different values , address now.
and i'm confused tmp has smaller address array.
so question is:
- what happen if declare array of length zero?
 - why these 2 codes works different? (they same me :) )
 
this called "undefined behavior". after declaring, in case
int tmp[0];   the next thing happens is:
tmp[0]=1;   since tmp[0] not exist, undefined behavior. problem not array declared size 0 (that's not kosher on own merits, not issue here), undefined behavior result of overwriting memory past end of array.
Comments
Post a Comment