Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
//initialization
int validtracks[17][2] = {{1,1}, {1,3}, {1,6},{2,3},{2,6},{3,4},{3,6},{3,8}, 
{4,2},{4,3},{4,7},{5,3},{5,5},{6,1}, {6,3},{7,1},{7,3}};


//main code
while (matchtrack == 0) 
{
     rndint = rand() % 7 + 1;

     for (int r = 1; r < 18; r++)
        {

        if (validtracks[r][2] == rndint && validtracks[r][1] ==   
            rndtracks[1] && matchtrack == 0)
             {
             matchtrack = 1;
              }

        }
}

What I have tried:

I have narrowed the problem down to the conditional:

if (validtracks[r][2] == rndint && validtracks[r][1] ==rndtracks[1] && matchtrack ==0)
            {
            matchtrack = 1;
            }


For some reason it's detecting a match with elements in the array, when it shouldn't be:
//initialized array
int validtracks[17][2] = {{1,1}, {1,3}, {1,6},{2,3},{2,6},{3,4},{3,6},{3,8}, 
{4,2},{4,3},{4,7},{5,3},{5,5},{6,1}, {6,3},{7,1},{7,3}};
Posted
Updated 2-May-18 16:47pm

1 solution

Quote:
Why is the conditional (highlighted in the code below) detecting a match for values that are NOT defined in the initialized 2d array ....?

Because in C/C++, 'NOT defined' does not exist. Because C/C++ is unchecked, you are responsible of ensuring that you always access valid positions in your arrays. From C/C++ point of view, as long as you try to access a position you own in memory, it is correct.
For an array int validtracks[17][2], C/C++ allocate a continuous position of 34 integers in memory. To access any position in the array validtracks[x][y], the formula of offset is x*2+y. So when you try to access the invalid validtracks[x][2], in fact you access the valid validtracks[x+1][0] if exist, or something else.

Any position in memory have a value, simply, if you did not initialized it, you just don't know what is the the value, you can be lucky or not.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900