1

I created this function that scans a 2D array for vertical pairs, where row = 20 and column = 30. To clarify random characters from A to Z are stored in each of the array's elements.

char function3 (char randchar_array[ROW] [COLUMN]) 

{
int r = 0 ;
int c = 0 ;
int vertpairs = 0;

 for (r = 0; r < ROW ; r++)
 {
     for (c = 0; c < COLUMN -1; c++)
     {
       {
       if(randchar_array[r][c] == randchar_array[r+1][c])
         vertpairs++;
       }
     }
  }

  return (vertpairs);
}

My question is: Is the -1 necessary for the 2nd for statement " for (c = 0; c < COLUMN -1; c++)."

1 Answer 1

3

No, from the code (which compares vertically) it seems the - 1 should be on the outer loop instead.

Now it will compare at randchar_array[ROW - 1 + 1][c] which is out of bounds, and gives undefined behavior.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, could you take a look at the rest of the code and tell me what you think needs to be fixed/changed. I'm new to programming and am having a hard time figuring out what I'm doing wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.