0

I want to return in my function the n - size of the matrix - and the matrix itself at *p.

The file is something like, for example,

3
10
20
30

this is how I call it:

main( )
{
    int n, *p;
    n = Load_Matrix( p );
}

int Load_Matrix( int **ptr )
{
    FILE *fp;
    int i, a, n;
    fp = fopen( "matrix.txt", "r" );
    if ( fp == NULL )
    {
        printf( "Cannot load file\n" );
        return 0;
    }
    fscanf( fp, "%d", n );
    *ptr = (int *) malloc( sizeof(int) *n );
    for ( i = 0; i<n; i++ )
    {
        fscanf( fp, "%d", &a );
        *( ptr + i ) = a;
    }
    fclose( fp );
    return n;
}
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
kazama
  • 211
  • 1
  • 2
  • 10

2 Answers2

1

You are incrementing the address of the passed pointer ptr, instead of the pointer itself.

The line *( ptr + i ) = a; is wrong. It should be (*ptr)[i] = a;

Also pass the address of the pointer in main

int n, *p;
n = Load_Matrix( &p );

And the line fscanf( fp, "%d", n ); is wrong. fscanf() need an address of n.

And a number of small errors are still present, like function prototype for Load_Matrix(), int main( void ), check all return values

this
  • 5,229
  • 1
  • 22
  • 51
  • this one solved me other problems too.. bad this is actually an exercise at my college and it say not to use at all this [] so how can i rewrite this (*ptr)[i]=a; – kazama Mar 17 '14 at 22:09
0

this :

 n=Load_Matrix(p); 

should be

n=Load_Matrix(&p);

as Load_Matrix expects to get pointer to pointer. also this

 fscanf( fp, "%d", n );

should be

  fscanf( fp, "%d", &n );
Dabo
  • 2,371
  • 2
  • 18
  • 26