尝试通过向量定义矩阵

Trying to define a matrix by a vector

我正在尝试使用以下语法定义包含向量的矩阵:

typedef int vect[dim];
typedef int vect mat[dim];

最后,我想要一个使用两个向量的矩阵,尽管我得到以下错误:

variably modified 'vect' at file scope typedef int vect[dim];

expected '=', ',', ';', 'asm' or '__attribute__' before 'mat' typedef int vect mat[dim];

这个 typedef 定义

typedef int vect mat[dim];

无效,因为类型说明符 int 由于此 typedef

而出现两次
typedef int vect[dim];

你应该写

typedef vect mat[dim];

其次(C 标准,6.7.8 类型定义)

2 If a typedef name specifies a variably modified type then it shall have block scope.

但是,您似乎在文件范围内的 typedef 中定义了一个可变修改类型。所以编译器应该会报错。

如果您需要具有可变修改类型的 typedef,则在块作用域中定义它,例如在需要使用它的函数的开头。

这是一个演示程序。

#include <stdio.h>

void f( size_t dim )
{
    for ( ; dim != 0; --dim )
    {
        typedef int vect[dim];
        typedef vect mat[dim];

        mat m;

        printf( "sizeof( m ) = %zu\n", sizeof( m ) );
    }
}

int main(void) 
{
    f( 5 );

    return 0;
}

它的输出是

sizeof( m ) = 100
sizeof( m ) = 64
sizeof( m ) = 36
sizeof( m ) = 16
sizeof( m ) = 4

或者另一个例子。

#include <stdio.h>

void fill( size_t dim, int m[][dim] )
{
    for ( size_t i = 0; i < dim; i++ )
    {
        for ( size_t j = 0; j < dim; j++ )
        {
            m[i][j] = i * dim + j;
        }
    }
}

void output( size_t dim, int m[][dim] )
{
    for ( size_t i = 0; i < dim; i++ )
    {
        for ( size_t j = 0; j < dim; j++ )
        {
            printf( "%2d ", m[i][j] );
        }
        putchar( '\n' );
    }
}


int main(void) 
{
    printf( "Enter the dimension of a square matrix: " );
    size_t dim;

    scanf( "%zu", &dim );

    typedef int vect[dim];
    typedef vect mat[dim];

    mat m;

    fill( dim, m );
    output( dim, m );

    return 0;
}

程序输出可能看起来像

Enter the dimension of a square matrix: 4
 0  1  2  3 
 4  5  6  7 
 8  9 10 11 
12 13 14 15