C - 在随机生成的二维数组中查找素数

标签 c arrays multidimensional-array primes

在 C 中,我有一个随机生成的 20x20 数组。我可以很好地排序和显示它,但我需要从每一行中取出素数并将它们放入自己的数组中。它需要使用 main 之外的函数来完成。

问题是,无论我尝试什么,我都找不到正确的语法来对数组执行算术以查找素数,我总是得到“二进制 % 的无效操作数(有 'int *' 和 'int ')“错误。我不确定是否有办法取消引用数组以对其执行算术。这是一些代码:

#include <stdio.h>
#include <stdlib.h>

#define TOTAL_ROWS 20
#define TOTAL_COLUMNS 20

void fillMatrix(int A[TOTAL_ROWS][TOTAL_COLUMNS], int *set_rows, int *set_columns)
{
    int rows = 20, columns = 20;
    for(int i = 0; i < rows; i++)
        for(int j = 0; j < columns; j++)
            A[i][j] = rand() % 500;

    *set_rows = rows;
    *set_columns = columns;
}




void sortMatrix(int A[TOTAL_ROWS][TOTAL_COLUMNS], int rowsize, int colsize)
{
    for(int r = 0; r < rowsize; r++)
        qsort(A[r], colsize, sizeof(int), compare);
    }



void displayArray(int A[TOTAL_ROWS][TOTAL_COLUMNS], int rows, int columns)
{
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < columns; j++)
            printf("%3i ", A[i][j]);
        printf("\n");
    }
}

void findPrimes(int A[TOTAL_ROWS][TOTAL_COLUMNS], int rows, int columns)  
{
int n,c,sum,count;
    for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < columns; j++){
                for(i=0;i<n;i++)
                    {
                        c=0;
                        for(j=2;j<A[i];j++)
                        {
                            if(A[i]%j==0) //where "invalid operands to binary % (have 'int *' and 'int')" happens 
                            {
                                   c=1;
                                   break;
                            }
                        }
                         if(c==0)
                         {
                            printf("%d\t",A[i]);
                            sum=sum+A[i];
                            count++;
                         }
                    }
            }
        }
}



int main(void)
{
    int A[TOTAL_ROWS][TOTAL_COLUMNS];
    int rows, columns;
    fillMatrix(A, &rows, &columns);
    sortMatrix(A, rows, columns);
    displayArray(A, rows, columns);
    findPrimes(A, rows, columns);
    return  0;
}

最佳答案

问题是 A[i] 是 2D 数组的一整行,因此它本身就是一个标准(1D)数组(当在大多数方面都使用过,因此出现了该消息)。

您想要使用A[i][j]来获取特定单元格的int值。

但是,虽然这允许您的代码编译,但它仍然无法正常工作。以下是需要修复的其他问题的列表:

  • 嵌套循环均在 i 上进行迭代。这显然是一个错误,并且会产生意想不到的结果。
  • 使用未初始化的自动变量nsumcount。后两者应初始化为0;你需要明确地这样做。我不确定 n 想要做什么。
  • 代码风格。虽然这不会导致您的代码直接失败,但不一致的缩进和缺乏封装的困惑使得更容易犯错误。

关于C - 在随机生成的二维数组中查找素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526125/

相关文章:

二维指针数组中的单元格索引

php - 引用 - 这个错误在 PHP 中意味着什么?

Java,如何按行和列拆分多维数组

.net - 带双括号 ()() 的 VB.NET 数组

c - 制作一个函数来更新二维数组井字游戏表的 Action

c - 字典文件崩溃但编译正常

c - union 和通用功能

c - tcc "lvalue expected"错误

c - ADC通过PWM信号问题

java - 矩阵中最大的行或列