We help IT Professionals succeed at work.

c++ unassigned array

Troudeloup
Troudeloup asked
on
int array[5]

what if I didn't assign any values to array[4] before I access it? what happens when i access it?

it is possible to check if an entry is assigned?
Comment
Watch Question

Senior Software Engineer (Avast)
CERTIFIED EXPERT
Commented:
>> what if I didn't assign any values to array[4] before I access it? what happens when i access it?
It depends. If it's a global variable it'll automatically be initialized to 0; else it'll contain random data.

>> it is possible to check if an entry is assigned?
Not really, no. Always initialize your data. The code below will set every element in the array to be 0.
int array[5] = {0};
evilrixSenior Software Engineer (Avast)
CERTIFIED EXPERT

Commented:
More in initializing arrays can be found here: http://www.cplusplus.com/doc/tutorial/arrays.html
evilrixSenior Software Engineer (Avast)
CERTIFIED EXPERT

Commented:
Additionally, since you are using C++ you might want to consider using std::vector<int> instead.
http://www.cplusplus.com/reference/stl/vector/

Commented:
Exactly as evilrix says ... you could also set the values in this array (as it's an int array) using memset, e.g.

    memset(array, -1, sizeof(array));

That will set each member's value to -1 - which you could use as indicating an item's not been assigned to, if -1 isn't a valid value.  The value (-1 here) is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.