我使用malloc
函数编写了一些代码并生成结果文件,但它显示了分段错误。你能提一些建议吗?
获得m
和n
值,并使用m
n
矩阵制作a_ij=i*i+j*j
。
#include"stdio.h"
#include"stdlib.h"
#include"malloc.h"
int i,j,m,n;
float **a, sum;
float func(float **a,int m,int n);
FILE *out;
int main()
{
printf("Enter the value of m and n: \n");
scanf("%d",&m);
scanf("%d",&n);
for(i=0; i<m; i++) a[i]=(float *)malloc(n*sizeof(float));
printf("o\n");
for(i=0; i<m; i++)
for(j=0; j<n; j++)
a[i][j]=0;
func(a,m,n);
printf("\n matrix A: \n");
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
printf("%f\t", a[i][j]);
printf("\n");
sum=sum+a[i][j];
}
printf("\n SUM: %f",sum);
out=fopen("outFile","w");
fprintf(out,"\n matrix A: \n");
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
printf("%f\t", a[i][j]);
printf("\n");
}
fprintf(out,"\n SUM: %f", sum);
fclose(out);
return 0;
}
float func(float **a,int m,int n)
{
for(i=0; i<m; i++)
for(j=0; j<n; j++)
a[i][j]=(i+1)*(i+1)+(j+1)*(j+1);
return;
}
如何纠正这个程序?
答案 0 :(得分:1)
您忘记在程序开头分配指针数组a
。
首先分配包含行指针的数组:
a = (float**)malloc(m*sizeof(float*));
然后为每一行分配内存:
for(i=0; i<m; i++) {
a[i] = (float*)malloc(n*sizeof(float));
}
答案 1 :(得分:1)
你忘了将a
点定义在某处。换句话说,您永远不会初始化a
。
答案 2 :(得分:0)
这是纠正后的程序:
#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"
int i, j, m, n;
float **a, sum;
void func( float **a, int m, int n );
FILE *out;
int main()
{
printf( "Enter the value of m and n: \n" );
scanf("%d",&m);
scanf("%d",&n);
a = ( float** ) malloc( m * sizeof( float* ) );
for( i = 0; i < m; i++ )
{
a[ i ] = ( float * ) malloc( n * sizeof( float ) );
}
printf( "o\n" );
for( i = 0; i < m; i++ )
{
for( j = 0; j < n; j++ )
{
a[ i ][ j ] = 0;
}
}
func(a,m,n);
printf("\n matrix A: \n");
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
printf( "%f\t", a[ i ][ j ] );
sum = sum + a[ i ][ j ];
}
printf( "\n" );
}
printf( "\n SUM: %f", sum );
out = fopen( "outFile","w" );
fprintf( out, "\n matrix A: \n" );
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
fprintf( out, "%f\t", a[ i ][ j ] );
}
fprintf( out, "\n");
}
fprintf( out,"\n SUM: %f", sum );
fclose( out );
for( i = 0; i < m; ++i )
{
free( a[ i ] );
}
free( a );
return 0;
}
void func( float **a, int m, int n )
{
for( i = 0; i < m; i++ )
{
for( j = 0; j < n; j++ )
{
a[ i ][ j ] = ( i + 1 ) * ( i + 1 ) + ( j + 1 ) * ( j + 1 );
}
}
}
更改:
还有另一个问题:
== 8958 ==读取大小4无效 == 8958 == at 0x109024:main(test.c:39) == 8958 ==地址0x51e4098在大小为8的块之后是0字节 == 8958 ==在0x4C2C840:malloc(在/usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so中) == 8958 == by 0x108E30:main(test.c:21)
与数组上的不正确迭代有关
希望它会有所帮助:)