[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 498
  • Last Modified:

c++ unassigned array

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?
0
Troudeloup
Asked:
Troudeloup
  • 3
1 Solution
 
evilrixSenior Software Engineer (Avast)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};
0
 
evilrixSenior Software Engineer (Avast)Commented:
More in initializing arrays can be found here: http://www.cplusplus.com/doc/tutorial/arrays.html
0
 
evilrixSenior Software Engineer (Avast)Commented:
Additionally, since you are using C++ you might want to consider using std::vector<int> instead.
http://www.cplusplus.com/reference/stl/vector/
0
 
peetmCommented:
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.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now