I have a problem if i do it with realloc it doesn-t work should i count the non NULL numbers and use malloc?
just that i thought that it would be more practical too use realloc....
the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int lekepez(int **, int, int, int *, int *, int *);
int keres(int ,int, int, int *, int *, int *);
int main()
{
int **a, i,j,n,m,x;
srand(time(NULL));
printf("m=");
scanf("%d",&m);
printf("n=");
scanf("%d",&n);
a=(int**) malloc(m*(sizeof (int *)));
for(i=0;i<m;++i) a=(int*) malloc(n*(sizeof (int)));
for(i=0;i<m;++i)
for(j=0;j<n;++j)
{
x=rand()%2;
if(x) a[j]=rand()%90+10;
else a[j]=x;
}
for(i=0;i<m;++i)
{
for(j=0;j<n;++j)
printf("%3d",a[j]);
printf("\n");
}
printf("\n\n");
int k,*sor,*oszlop,*ertek;
sor=(int *) malloc((m*n)*sizeof(int));
oszlop=(int *) malloc((m*n)*sizeof(int));
ertek=(int *) malloc((m*n)*sizeof(int));
k=lekepez(a,m,n,sor,oszlop,ertek);
free(a);
for(i=0;i<k;++i) printf("%3d",sor);
printf("\n");
for(i=0;i<k;++i) printf("%3d",oszlop);
printf("\n");
for(i=0;i<k;++i) printf("%3d",ertek);
printf("\n\n");
for(i=0;i<m;++i)
{
for(j=0;j<n;++j)
printf("%3d",keres(i,j,k,sor,oszlop,ertek));
printf("\n");
}
return 0;
}
int lekepez(int **a,int m, int n, int *sor, int *oszlop, int *ertek)
{
int i,j,k=0;
for(i=0;i<m;++i)
for(j=0;j<n;++j)
if(a[j])
{
/*if(k)
{
sor=(int *) realloc(sor,(k+1)*sizeof(int));
oszlop=(int *) realloc(oszlop,(k+1)*sizeof(int));
ertek=(int *) realloc(ertek,(k+1)*sizeof(int));
}*/
sor[k]=i;
oszlop[k]=j;
ertek[k]=a[j];
++k;
}
return k;
}
int keres(int i, int j, int k, int *sor, int *oszlop, int *ertek)
{
int p;
for(p=0;p<k;++p)
if (sor[p]==i && oszlop[p]==j) return ertek[p];
else if(sor[p]>i) return 0;
}