문제

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;
}
도움이 되었습니까?

해결책

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 :

 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 );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top