简体   繁体   English

声明和初始化动态分配的二维数组的最佳方法是什么?

[英]What is the best way to declare and initialize a 2D array dynamically allocated?

I tried in this way, but I don't know if it's the best way to do this:我尝试过这种方式,但我不知道这是否是最好的方法:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ROW 5
#define COL 5

int *matrix;

int main(int argc, const char * argv[])
{
    matrix = malloc(ROW * COL * sizeof(int));
    memset(matrix, 0, ROW * COL * sizeof(int));

    return 0;
}

(I'm ignoring the word "best" in your question title) (我忽略了您问题标题中的“最佳”一词)

  1. Try to avoid global variables .尽量避免全局变量 If you need matrix in main() , then declare it in main() and pass it to other functions as necessary.如果您需要main()中的matrix ,则在main() () 中声明它并根据需要将其传递给其他函数。

  2. As @Vlad's answer mentions - if you specifically want to set your array to zero, you can combine your malloc() and memset() calls into a single calloc() ("clear-allocate" if you will) call.正如@Vlad 的回答所提到的——如果你特别想将你的数组设置为零,你可以将你的malloc()memset()调用组合成一个calloc() (“clear-allocate”,如果你愿意的话)调用。

  3. If you know the matrix dimensions in advance, you might just allocate the matrix on the stack, eg:如果您事先知道矩阵尺寸,您可能只需在堆栈上分配矩阵,例如:

     int main(int argc, const char * argv[]) { int matrix[ROW * COL] = { 0 }; // etc. etc. }

    (which should set the whole array to zero as well.) (这也应该将整个数组设置为零。)

    if, on the other hand, the matrix is quite large, then even for dimensions known apriori it makes more sense to allocate dynamically, because stack space is limited.另一方面,如果矩阵非常大,那么即使对于先验已知的维度,动态分配也更有意义,因为堆栈空间是有限的。

  4. It is not a good idea to allocate every column or every row separately with malloc() .使用malloc()分别分配每一列或每一行并不是一个好主意。 Even if you wanted your matrix to be used in the form matrix[i][j] , you would still use a single allocation - but allocate space for the actual data as well as a sequence of pointers to column beginnings.即使您希望您的矩阵以matrix[i][j]形式使用,您仍然会使用单个分配 - 但为实际数据分配空间以及指向列开头的指针序列。

Further reading:进一步阅读:

It is better to deal with a matrix when it is represented as a two-dimensional array.当矩阵表示为二维数组时,最好处理它。

Instead of calling malloc and then memset manually you can substitute them for a call of calloc .除了手动调用mallocmemset之外,您还可以将它们替换为calloc的调用。

So you can write in main (there is no need to declare the pointer in the file scope)所以你可以在main中写(不需要在文件范围内声明指针)

int ( *matrix )[COL] = calloc( 1, sizeof( int[ROW][COL] ) );

Using such an array makes code more clear.使用这样的数组可以使代码更加清晰。 For example to output the matrix you can write例如到 output 矩阵你可以写

for ( size_t i = 0; i < ROW; i++ )
{
    for ( size_t j = 0; j < COL; j++ )
    {
        printf( "%d ", matrix[i][j] );
    }
    putchar( '\n' );
}

To conclude about difficulties of using a one-dimensional array imagine how will look a code of multiplication of two matrices.总结一下使用一维数组的困难,想象一下两个矩阵相乘的代码。

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

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