[英]When I try to run it the program crashes and I don't know why
I want to return in my function the n
- size of the matrix - and the matrix itself at *p
. 我想在函数中返回矩阵的
n
大小-以及矩阵本身在*p
。
The file is something like, for example, 该文件例如是
3
3
1010
2020
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. 您正在增加传递的指针ptr的地址,而不是指针本身。
The line *( ptr + i ) = a;
*( ptr + i ) = a;
is wrong. 是错的。 It should be
(*ptr)[i] = a;
应该是
(*ptr)[i] = a;
Also pass the address of the pointer in main 还要在main中传递指针的地址
int n, *p;
n = Load_Matrix( &p );
And the line fscanf( fp, "%d", n );
行
fscanf( fp, "%d", n );
is wrong. 是错的。 fscanf() need an address of n.
fscanf()需要一个n的地址。
And a number of small errors are still present, like function prototype for Load_Matrix(), int main( void ), check all return values 而且仍然存在许多小错误,例如Load_Matrix()的函数原型,int main(void),检查所有返回值
this : 这个 :
n=Load_Matrix(p);
should be 应该
n=Load_Matrix(&p);
as Load_Matrix
expects to get pointer to pointer. 因为
Load_Matrix
希望获得指向该指针的指针。 also this 还有这个
fscanf( fp, "%d", n );
should be 应该
fscanf( fp, "%d", &n );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.