2D array using a function to scan for pairs

一笑奈何 提交于 2020-01-05 15:05:54

问题


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:


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.



来源:https://stackoverflow.com/questions/19787191/2d-array-using-a-function-to-scan-for-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!