Pooya
Pooya

Reputation: 1012

influence of array pointer

When we have:

#include <iostream>
using namespace std;

int main()
{
    int a[100];
    cout << a[0] << endl;
}

I get "1".

But when I change it like this:

#include <iostream>
using namespace std;

int main()
{
    int a[100];
    int* b = &a[0];
    cout << a[0] << endl;
    cout << *b << endl;     
}

I get something like "-1219451320", which changes after each run.

What was the influence of b variable so a[0] got changed? For example now, If I change it to previous code, the result will be "1" again.

in both of the states, the array was not initialized! so there shouldn't be difference like this. for example in the first code, if we got "-12242311231", it wouldn't be strange but now ...

Upvotes: 0

Views: 61

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145419

You have not initialized the array, so the values are (or can be) arbitrary.

The standard calls them indeterminate values.

With two different programs, which you have, you can expect to get two different values, or the same value, with no discernible pattern or reason (it's arbitrary). You can even get different values from two runs of the same program. To initialize, just write

int a[100] = {};  // All zeroes. :-)

Instead of raw arrays, consider using std::vector, e.g.

#include <vector>

// ...
std::vector<int> a( 100 );    // All zeroes

It initializes automatically and always.

And it can also be resized.

Upvotes: 5

Related Questions