这是一个演示程序,显示如何为您的结构分配内存。
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int **mymatrix; // will have the matrix
size_t row; // this one is for row
size_t column; // will hold column number
} mystruct;
int init( mystruct *s,size_t rows,size_t cols )
{
s->mymatrix = malloc( rows * sizeof( int * ) );
int success = s->mymatrix != NULL;
if ( success )
{
size_t i = 0;
while ( i < rows && ( s->mymatrix[i] = calloc( cols,sizeof( int ) ) ) != NULL )
{
i++;
}
success = i == rows;
if ( success )
{
s->row = rows;
s->column = cols;
}
else
{
for ( size_t j = 0; j < i; j++ )
{
free( s->mymatrix[j] );
}
free( s->mymatrix );
s->mymatrix = NULL;
s->row = 0;
s->column = 0;
}
}
return success;
}
void fill( mystruct *s,int value )
{
for ( size_t i = 0; i < s->row; i++ )
{
for ( size_t j = 0; j < s->column; j++ )
{
s->mymatrix[i][j] = value;
}
}
}
int main(void)
{
size_t n = 1;
mystruct *s = malloc( n * sizeof( mystruct ) );
if ( init( s,5,5 ) ) fill( s,5 );
mystruct *tmp = realloc( s,( n + 1 ) * sizeof( mystruct ) );
if ( tmp != NULL )
{
s = tmp,init( s + n,10,10 );
fill( s + n,10 );
++n;
}
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < s[i].row; j++ )
{
for ( size_t k = 0; k < s[i].column; k++ )
{
printf( "%d ",s[i].mymatrix[j][k] );
}
putchar( '\n' );
}
putchar( '\n' );
}
for ( size_t i = 0; i < n; i++ )
{
if ( s[i].mymatrix != NULL )
{
for ( size_t j = 0; j < s[i].row; j++ )
{
free( s[i].mymatrix[j] );
}
free( s[i].mymatrix );
}
}
free( s );
return 0;
}
程序输出为
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
5 5 5 5 5
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10
本文链接:https://www.f2er.com/3145901.html