如何计数特定字符的出现在2D数组在C语言?



我有一个数组[8][8]

char d[ROWS][COLS] = {
{0, 2, 0, 2, 0, 2, 0, 2},
{2, 0, 2, 0, 2, 0, 2, 0},
{0, 2, 0, 2, 0, 2, 0, 2},
{1, 0, 1, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 0, 1, 0, 1},
{3, 0, 3, 0, 3, 0, 3, 0},
{0, 3, 0, 3, 0, 3, 0, 3},
{3, 0, 3, 0, 3, 0, 3, 0}};

int countOccurrences(char d[ROWS][COLS], int i, int j, int res)
{
res = 0;
for (i=0; i<=ROWS; i++){
for(j=0; j<=COLS; j++){
if ('2' == d[ROWS][COLS])
res++;

}
}      
return res;
printf("score%d", res);
} 

我的代码不起作用,我需要找到并计算2D数组中的出现次数并将其打印出来

我做了一个注释,但我也将继续使用固定函数进行响应。我将指出代码中的三个主要问题:

  1. 在你的代码中,你有数组内的数字,但然后你尝试比较一个字符到一个数字('2' == 2是假的),所以这意味着你的结果将是0在所有
  2. 打印语句在return之后,这意味着它实际上不会运行。
  3. if语句if (2 == d[ROWS][COLS])总是检查位置ROWSCOLS的数字。第一个问题是ROWSCOLS没有改变位置,这是一个常数;你要检查位置ij。其次,由于C中的数组是从零开始的,在位置[ROWS][COLS]访问d实际上会指向一些未知的内存空间,因为这超出了数组的范围,但这只是一个有趣的事实。

下面的代码应该可以解决我上面指出的问题:

char d[ROWS][COLS] = {
{0, 2, 0, 2, 0, 2, 0, 2},
{2, 0, 2, 0, 2, 0, 2, 0},
{0, 2, 0, 2, 0, 2, 0, 2},
{1, 0, 1, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 0, 1, 0, 1},
{3, 0, 3, 0, 3, 0, 3, 0},
{0, 3, 0, 3, 0, 3, 0, 3},
{3, 0, 3, 0, 3, 0, 3, 0}};
int countOccurrences(char d[ROWS][COLS], int i, int j, int res) {
res = 0;
// NOTICE that it is now i < ROWS and j < COLS instead of
// i <= ROWS and j <= COLS to deal with what I mentioned
// before about the zero-based indexing in C, which means
// we need to stop BEFORE ROWS and COLS
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (2 == d[i][j])
res++;
}
}      
printf("score%d", res);
return res;
}

你的代码有一些问题:

  • 您有一个char'2',它将转换为您的系统使用的任何字符编码,在我的情况下,ASCII,这将由值50保存,并且您将其与值2进行比较,这将返回false
  • 你每次比较d[ROWS][COLS],这可能不是你想要的。
  • 在你的循环中,有时它会尝试访问d[ROW][...],d[...][COL],这会产生一个越界错误。
  • 你给函数设置了太多不必要的参数
  • 你的returnprintf()之前,所以printf()永远不会执行。

建议代码:

char d[ROWS][COLS] = {
{'0', '2', '0', '2', '0', '2', '0', '2'},
{'2', '0', '2', '0', '2', '0', '2', '0'},
{'0', '2', '0', '2', '0', '2', '0', '2'},
{'1', '0', '1', '0', '1', '0', '1', '0'},
{'0', '1', '0', '1', '0', '1', '0', '1'},
{'3', '0', '3', '0', '3', '0', '3', '0'},
{'0', '3', '0', '3', '0', '3', '0', '3'},
{'3', '0', '3', '0', '3', '0', '3', '0'}};

int countOccurrences(char anotherName[], int ROWS, int COLS)
{
int res = 0;
for (int i=0; i<ROWS; i++){
for(int j=0; j<COLS; j++){
if ('2' == anotherName[i][j])
++res;

}
}      
printf("score%d", res);
return res;
} 
// You should call it like this: int something = countOccurrences(d, ROWS, COLS);