i try make a program to show the largest number in column a 2d array, but this program have a problem which cannot produce the desired result. in my compiler says :
3 5 [Note] expected 'int *' but argument is of type 'int (*)[(sizetype)(b)]'
and this my code :
#include<stdio.h>
int array2d(int *x, int a, int b){
int i,j;
int max[j];
for(i=0; i<a ; i++){
max[j]= *x;
for(j=0; j<b ; j++){
if(*x>max[j])
{
max[j]=*x;
}
}
printf("\nthe maximum value of each column is : %d", max[j]);
}
int main(){
int a,b,i,j;
printf("enter the size of array (rows) & (column) : ");
scanf("%d %d",&a,&b);
int x[a][b];
printf("enter the number : ");
for ( i = 0; i < a; i++)
{
for ( j = 0; j < b; j++)
{
scanf("%d",&x[i][j]);
}
}
array2d(x,a,b);
return 0;
}
the program input :
4 4
and input number :
1 3 2 1
8 4 3 2
1 2 3 4
9 8 7 6
And expected this output :
9 8 7 6
What should I do to fix it? I need your opinion and maybe anyone wants to help me to write the right code.
Here you have a working example:
See the pointer arithmetics.
void printArray(int *x, size_t a, size_t b)
{
if(x && a && b)
{
for(size_t i = 0; i < a; i++)
{
for(size_t j = 0; j < b; j++)
printf("%d\t", *(x + i * a + j));
printf("\n");
}
}
}
void array2d(int *x, size_t a, size_t b)
{
if(x && a && b)
{
for(size_t i = 0; i < b; i++)
{
int max = *(x + i);
for(size_t j = 0; j < a; j++)
{
if(*(x + j * a + i) > max)
{
max = *(x + j * a + i);
}
}
printf("\nthe maximum value of each column is : %d", max);
}
}
}
int main(void)
{
size_t a = 0,b = 0;
printf("enter the size of array (rows) & (column) : ");
scanf("%d %d",&a,&b);
printf("\n");
int x[a][b];
srand(time(NULL));
for (size_t i = 0; i < a; i++)
{
for (size_t j = 0; j < b; j++)
{
x[i][j] = rand() % 1000;
}
}
printArray(*x, a, b);
array2d(*x, a, b);
return 0;
}