Reputation: 1
I am trying to make a program that makes simple things. Actually, I know how to do it but in an easier way without pointers and stuff. However, I wondered how I could do it differently (like I did below). Obviously, there is something I miss about pointers, I did the math, but still I cannot get its philosophy. Thank you!
long *read_array(int n1, int n2)
{
int i, j;
long a[n1][n2];
for(i=0;i<n1;i++)
for(j=0;j<n2;j++)
printf("Fill the table");
a[i][j]=GetLong();
return a;
}
long *Min_of_Rows(int m, int n, long *a)
{
long B[];
int i, j;
for(i=0;i<m;i++)
B[i]=a[i][0];
for(j=0;j<n;j++)
if (a[i][j]<B[i])
B[i]=a[i][j];
return B;
}
void *Print_B_array (int M, long *b)
{
int i;
for(i=0; i<M; i++)
printf("%ld\n",b[i]);
}
main()
{
long *a, *b;
int n1, n2;
printf("give rows");
n1=GetInteger();
printf("give columns");
n2=GetInteger();
a=read_array(n1, n2);
b=Min_of_rows(n1, n2, a);
Print_B_Array(n1, b);
}
Upvotes: -1
Views: 82
Reputation: 40145
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long *read_array(int n1, int n2){
int i, j;
long a[n1][n2];
printf("Fill the table\n");
for(i=0;i<n1;i++){
for(j=0;j<n2;j++){
a[i][j]=GetLong();
}
}
long *ret = malloc(sizeof(a));
memcpy(ret, a, sizeof(a));
return ret;
}
long *Min_of_Rows(int m, int n, long *a){
long *B = malloc(m*sizeof(*B));
int i, j;
long (*A)[n] = (void*)a;
for(i=0;i<m;i++){
B[i]=A[i][0];
for(j=0;j<n;j++){
if(A[i][j]<B[i])
B[i]=A[i][j];
}
}
return B;
}
void *Print_B_Array (int M, long *b){
int i;
for(i=0; i<M; i++)
printf("%ld\n", b[i]);
}
int main(void){
long *a, *b;
int n1, n2;
printf("give rows:");
n1=GetInteger();
printf("give columns:");
n2=GetInteger();
a=read_array(n1, n2);
b=Min_of_Rows(n1, n2, a);
printf("min of rows\n");
Print_B_Array(n1, b);
free(a);
free(b);
return 0;
}
Upvotes: 1