i am declaring a global array,and then assigning the values inside a if statement. But when i am using the array in another if statement the array has different values other than i assigned previously.
For example:
int arr[5];
xyz(bool p,bool q)
{
if(p)
{
for(int i=0;i<5;i++)
{
arr[i]=rand()%100;
}
}
if(q)
{
for(i=0;i<5;i++)
printf("%d",arr[i]);
}
}
can anyone help??
Well, if
p != qthen any changes you make toarrin the first conditional will not be printed when you enter the second conditional. Ifarrwas never initialized, it will almost certaninly not have the values you expect.Edit: Based on your comment below, Try using a
std::vector<int>instead of a C style integer array, as in:Also a couple suggestions:
arra local variable and pass it as a parameter where needed. This helps people looking at your code know what it needs and what it accesses without having to actually dig through the code to see it all. It’s possible (perhaps even likely) that something else is changingarrwithout you knowing it. If you always pass arguments and refrain from using globals, this will help you discover where it’s being changed.So, combining these I would recommend doing something like: