How to pass 2D array (matrix) in a function in C?

前端 未结 5 631
旧时难觅i
旧时难觅i 2020-11-22 01:31

I need to do this to persist operations on the matrix as well. Does that mean that it needs to be passed by reference?

Will this suffice?

void operate

5条回答
  •  北海茫月
    2020-11-22 02:11

    C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

    1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:

    #define ROWS 4
    #define COLS 5
    
    void func(int array[ROWS][COLS])
    {
      int i, j;
    
      for (i=0; i

    2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.

    void func(int** array, int rows, int cols)
    {
      int i, j;
    
      for (i=0; i

    3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:

    void func(int* array, int rows, int cols)
    {
      int i, j;
    
      for (i=0; i

    4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.

    #include 
    #include 
    #include 
    
    extern void func_vla(int rows, int cols, int array[rows][cols]);
    extern void get_rows_cols(int *rows, int *cols);
    extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);
    
    void func_vla(int rows, int cols, int array[rows][cols])
    {
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                array[i][j] = (i + 1) * (j + 1);
            }
        }
    }
    
    int main(void)
    {
        int rows, cols;
    
        get_rows_cols(&rows, &cols);
    
        int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
        /* error check omitted */
    
        func_vla(rows, cols, array);
        dump_array("After initialization", rows, cols, array);
    
        free(array);
        return 0;
    }
    
    void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
    {
        printf("%s (%dx%d):\n", tag, rows, cols);
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
                printf("%4d", array[i][j]);
            putchar('\n');
        }
    }
    
    void get_rows_cols(int *rows, int *cols)
    {
        srand(time(0));           // Only acceptable because it is called once
        *rows = 5 + rand() % 10;
        *cols = 3 + rand() % 12;
    }
    

    (See srand() — why call it only once?.)

提交回复
热议问题