【问题标题】:Creating sub-arrays of structs from within huge 2-dimensional struct array从巨大的二维结构数组中创建结构的子数组
【发布时间】:2020-03-20 19:27:03
【问题描述】:

我有一个结构定义为

struct KVPair {
    char key[7];
    double value;
};

我使用创建一个二维空结构数组

KVPair 矩阵[1000][500]={};

我稍后会填充这些值。

但是,我想要的是我应该能够从巨大的二维 1000x500 数组中创建子数组(二维)

意思是,如果在我的程序中的某个时候需要,我应该能够创建(或子分配或任何想使用的术语)类似

KVPair subMatrix[20][15]; 

这不应该使用新的内存块,而应该使用巨大数组中的现有块。有点租用内存空间。

然后又在某处下线

KVPair anotherSubMatrix[70][30];

当工作完成后,它也应该腾出租用的内存空间,以便下一个租户可以使用它。

在进行了一些 google 和 stackoverflow 搜索之后,使用一维数组执行此操作看起来有些直接,但二维数组看起来具有挑战性。

欢迎任何代码建议。

注意:我需要做这一切,因为在我的组织中不允许在堆上分配内存,而且我们严格遵循提到的错误准则 “数组声明应包含明确的大小规范”

【问题讨论】:

    标签: c++ c arrays pointers


    【解决方案1】:

    说,你被要求得到一个子矩阵'm',从第3行,第4列开始,维度为m[10][5];

    KVPair matrix[1000][500] = { ... some values ...};
    
    // first row index is '0', so row = 3 means 4th row
    // and first column index is '0', so column = 4 means 5th column
    
    int nRow = 10;
    int nCol = 5;
    int headRow = 3;
    int headCol = 4;
    
    KVPair *head = &matrix[headRow][headCol];
    KVPair **m = malloc(nRow * nCol * sizeof(KVPair *));
    
    for (int row = 0; row < nRow; row++) {
      for (int col = 0; col < nCol; col++) {
        *(m + nCol * row + col) = head + col;
        // printf("%s\n", (*m + nCol * row + col)->key);
        // getchar();
      }
    
      head += 500 - nCol;
    }
    
    free(m);
    

    n.b.新矩阵 'm' 将不包含原始矩阵的 值,而是包含指向相应结构元素的 指针。因此,如果你想取消引用并读取矩阵结构的值,你会喜欢;

    char *cTmp = (*m + nCol * row + col)->key;
    double dTmp = (*m + nCol * row + col)->value;
    

    附言将结构定义为 typedef 会让事情变得更容易:

    typedef struct {
        char key[7];
        double value;
    } KVPair;
    

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      相关资源
      最近更新 更多