In C, I have a randomly generated 20x20 array. I can sort and display it fine, but I need to take the prime numbers from each row and put them into their own array. It needs to be done with a function outside of main.
Problem is, no matter what I try I can't find the correct syntax to perform the arithmetic on the array to find the prime numbers, I always get "invalid operands to binary % (have 'int *' and 'int')" error. I'm not sure if there's a way to dereference the array to perform arithmetic on it. Here's some code:
#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;
}
The issue is that A[i]
is one entire row of the 2D array and is therefore itself a standard (1D) array (which decays to int*
when used in most ways, hence the message).
You want to use A[i][j]
to get the int
value of the specific cell.
But while this allows your code to compile, it still won't work properly. Here is a list of further problems to fix:
i
. This is clearly a mistake, and will produce unexpected results. n
, sum
, and count
. The latter two should be initialized to 0
; you need to do this explicitly. I'm not sure what n
is trying to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.