简体   繁体   English

在 C 中定义矩阵

[英]Define a matrix in C

I started to learn C and started a new argument: the matrices .我开始学习C并开始了一个新的论点: the matrices I saw that you can define a matrix in two different ways我看到你可以用两种不同的方式定义矩阵

WAY 1方式一

The first way using the subscript operator []第一种方式使用下标运算符[]

const int N = 3, M = 4;
int matrix[N][M];

but as this it is difficlt to pass the arguments in the functions becouse the the compiler has to know the matrix number of columns when it compiles the program.但是因为这样很难在函数中传递参数,因为编译器在编译程序时必须知道矩阵的列数。 so you have to do a function that works only for matrices with n columns所以你必须做一个只适用于n列矩阵的函数

int my_func( int matrix[][3], const int num_lines){...}

WAY 2方式2

The second way: use an array of arrays方式二:使用数组数组

const int N = 3, M = 4;
int** m = (int**) calloc(N, sizeof(int*))
for (int i = 0; i < N; i++){
    m[i] = (int*) calloc(M, sizeof(int))
}

So doing so you can easily pass the matrix pointer to a function an work fluently with it but the only problem is the efficency in the memory allocation and the the recall of values.这样做您可以轻松地将矩阵指针传递给一个函数,并可以流畅地使用它,但唯一的问题是内存分配的效率和值的调用。

WAY 3?方式3?

Actually i thought that there can be a third way and i was wondering if it was correct doing this其实我认为可以有第三种方式,我想知道这样做是否正确

const int N = 3, M = 4;
int array[N*M];
for (int i=0; i<N; i++){
    for (int j = 0; j<M; j++){
        printf("%d%d: %d\n", i, j, array[ i * M + j ]);
    }
}

Doing so by my point of view should be as efficency as the first way that i wrote but u can work with it more fluently in the functions becouse you need only to pass the lines and the columns as arguments从我的角度来看,这样做应该和我写的第一种方法一样有效,但你可以在函数中更流畅地使用它,因为你只需要将行和列作为参数传递

int my_func( const int* matrix, const int num_lines, const int num_columns){...}

Is the way 3 right? way 3对吗?

Is the way 3 right? way 3对吗?

From the memory management system, the way 3 is cheaper as you don't have too many allocations as in way 2 .从内存管理系统来看, way 3更便宜,因为您没有way 2太多分配。 But it is also limiting you in terms of maximum matrix size, which can be placed on the stack.但它也限制了您可以放置​​在堆栈上的最大矩阵大小。

If you take the best from way 2 and way 3 , you will end up with something like如果你从way 2way 3取得最好的结果,你最终会得到类似的结果

typedef struct  {
    unsigned M;
    unsigned N;
    int *data;
} Matrix;

Matrix create_matrix(unsigned M, unsigned N) {
    Matrix matrix;
    matrix.M = M;
    matrix.N = N;
    matrix.data = (int*) calloc(M * N, sizeof(int));
    return matrix;
}

int* get_matrix_element(Matrix *matrix, unsigned m, unsigned n) {
    return matrix->data + m * matrix->N + n;
}

void delete_matrix(Matrix *matrix) {
    free(matrix->data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM