dimanche 12 juin 2016

Array address in c++


I have some code like this :

int n;
cin >> n;
int array[n];

for (int i = 0; i < n; ++i) {
    cin >> array[i];  
}

int tmp[n - 1];
tmp[0] = 1;

With input : 1 10 I found that the value of array[0] was changed , instead of 10 it has the same with tmp[0].

Then I realized with that input the length of tmp[] became zero. So I print the address of array[] and tmp[] with:

printf("%dn %dn", array, tmp);

and found they had the same address.

I want to figure out what will happen if an array has a length of 0; so I tried this:

int array[1];
array[0] = 10;

int tmp[0];
tmp[0] = 1;

address:

array[]: 1363909056
tmp[]  : 1363909052

It looks just like the previous code (except the input part). But tmp[0] and array[0] has different values and address now.

And I'm really confused that tmp has smaller address then array.

So my question is:

  1. What will happen if I declare an array of length zero?
  2. Why these two codes works different? (they look the same to me :) )

Aucun commentaire:

Enregistrer un commentaire