编写一个函数,该函数在C中创建零的锯齿状二维数组

时间:2019-06-03 11:17:38

标签: c multidimensional-array jagged-arrays

我需要编写一个函数,以创建具有不同列数的行的2D数组。这是我尝试过的代码:

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

// program which allocates and returns a 2D int array full of zeros
int** make_zeros_jagged(int rows, int* array){
// dynamically allocate space for array
   int** result = malloc(sizeof(int*)*rows);
  if(result==NULL){
    printf("allocation error\n");
    return NULL;
  }

// dynamically allocate space for each row
  for(int row=0; row<rows;row++){
    // put error handling here
    int cols = (sizeof(array[row])/sizeof(int));
      printf("\n col: %d\n", cols); // ----------> always returns 1  
    result[row]=malloc(sizeof(int)*cols);
      for(int col=0; col<cols; col++){
      result[row][col]= 0;
      printf("%d ", result[row][col]);
    }
      printf("\n");
  }
    return result;
}


// driver code for building array
int main(void){

// declare and build 2d array
    int rows = 3;
    int row1[5] ;
    int row2[4] ;
    int row3[3] ;

    int* array[] = { row1, row2, row3 };
    int** newarray;
    newarray = make_zeros_jagged(3,*array);

  return 0;
}

预期结果应该是

0 0 0 0 0 
0 0 0 0 
0 0 0

但是我的代码返回

0 
0 
0

我想知道是否应该在函数的参数中包括每行的列数?但是我也不知道该怎么做。将列数读取到数组中?还是我的方法也可以工作?请帮我解决一下这个。谢谢!

1 个答案:

答案 0 :(得分:0)

您必须具有数组中每一行的列数。您的代码正在将指针传递给所需长度的数组,但是您无法从指针中获取它们的长度。

下面的代码获取行数,再加上一个带有每列长度的数组。它分配所需的锯齿状数组,并通过calloc调用将其初始化为零。

int** make_zeros_jagged_resizable(int rows, int* cols) {
    // Allocate array for pointers.
    int** result = malloc(sizeof(*result) * rows);
    if (result == NULL) {
        printf("allocation error\n");
        return NULL;
    }

    // Allocate each of the rows and fill them with zeros.
    for (int i = 0; i < rows; i++) {
        result[i] = calloc(cols[i], sizeof(*result[i]));

        if (result[i] == NULL) {
            printf("allocation error\n");
            // Free all the already-allocated rows.
            for (int j = 0; j < i; j++) {
                free(result[j]);
            }
            free(result);
            return NULL;
        }
    }

    return result;
}

请注意,上面的代码需要多次调用calloc,这对于大量行可能会很慢。同样,行在内存中可能彼此相距很远。如果您通常遍历整个2D数组,则最好在单个调用中分配整个int块,然后仅将指针设置为指向该单个块。这样做的缺点是无法再调整单个行的大小。请参见下面的代码。

int** make_zeros_jagged(int rows, int* cols) {
    // Allocate array for pointers.
    int** result = malloc(sizeof(*result) * rows);
    if (result == NULL) {
        printf("allocation error\n");
        return NULL;
    }

    // Compute total number of ints.
    size_t total_ints = 0;
    for (int i = 0; i < rows; i++) {
        total_ints += cols[i];
    }

    // Allocate array for ints, and zero it.
    // This assumes that you do not want to resize the rows
    // individually afterwards.
    int* space = calloc(total_ints, sizeof(*space));
    if (space == NULL) {
        printf("allocation error\n");
        free(result);
        return NULL;
    }

    // Fill the pointer array with pointers to the correct
    // parts of the int array.
    size_t pos = 0;
    for (int i = 0; i < rows; i++) {
        result[i] = &space[pos];
        pos += cols[i];
    }

    return result;
}