首页 > 解决方案 > 如何计算 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 数组中查找并计算出现次数并将其打印出来

标签: arraysc2d

解决方案


我发表了评论,但我也会继续使用固定功能做出回应。我将指出代码中的三个主要问题:

  1. 在您的代码中,您在数组中有数字,但随后您尝试将 char 与数字进行比较('2' == 2为 false),这意味着您的结果将全部为 0
  2. print 语句在之后return这意味着它实际上不会运行。
  3. if 语句if (2 == d[ROWS][COLS])总是检查位置ROWS和处的数字COLS。第一个问题是ROWS并且COLS没有改变位置,这是一个常数;你想检查位置ij。其次,由于 C 中的数组是从零开始的,因此d在位置访问[ROWS][COLS]实际上将指向一些未知的内存空间,因为这超出了数组的范围,但这只是一个有趣的事实。

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

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;
}

推荐阅读