gpt4 book ai didi

c - 如何为矩阵创建结构数组

转载 作者:行者123 更新时间:2023-12-04 11:02:03 25 4
gpt4 key购买 nike

基本上我有矩阵并想使用结构存储它们,但我需要使用动态内存分配来完成

typedef struct {
int mymatrix[5][5]; // the matrix
int column; // will hold column number
int row; // this one is for row
} mystruct;

那么我怎样才能把它变成动态内存风格呢?
typedef struct {
int **mymatrix; // will have the matrix
int column; // will hold column number
int row; // this one is for row
} mystruct;

是这样吗?如果是这样,我在哪里给出 mymatrix 的大小?我也想将它作为一个结构数组,但我想在创建新对象时扩展该数组。如果我的问题不清楚,任何想法都会有所帮助,谢谢。

最佳答案

这是一个演示程序,显示了如何为您的结构分配内存。

#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

关于c - 如何为矩阵创建结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58746245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com