簡體   English   中英

在標頭中聲明動態分配的二維數組,但不知道其維數

[英]Declaring in an header a dynamically allocated 2 dimensional array without knowing its dimensions

我需要在標頭中聲明動態分配的二維數組,而無需知道其尺寸,該尺寸將在函數內部建立。

在標題中,我要放置:

#define MAX_BARS_ALLOWED 20000
extern int Gregorian[][MAX_LINES_ALLOWED];  //it works

.cpp文件中的函數內:

int **Gregorian=new int*[NumLastItem+1][MAX_LINES_ALLOWED];  //this does NOT work, why ?

...並且由於我在函數內對其進行了初始化,因此它是否真的是全局的。

有人可以教我正確的方法嗎? 先感謝您 !!

這是我在堆上聲明可變大小矩陣的最喜歡的方法:您在每行的末尾分配一個額外的elem,以便知道邊界在哪里(有點像C樣式的字符串)。

int** read_matrix(int size_x, int size_y)
{
    int** matrix;
    matrix = calloc(size_x, 1+sizeof(int*)); // alloc one extra ptr
    for(int i = 0;i<size_x;i++) {
        matrix[i] = calloc(size_y, sizeof(int));
    }
    matrix[size_x] = NULL; // set the extra ptr to NULL

    /* populate the matrix if needed
    for(int i = 0;i<size_x;i++) {
        for(int j = 0;j<size_y;j++) {
            matrix[i][j] = i*10+j;
        }
    }
    */
    return matrix;
}

// keep looping until you find the NULL one
for( int i=0; first_matrix[i] != NULL; i++ ) {
    free( first_matrix[i] );
}
free( first_matrix );

這個片段是從那里復制的: int矩陣,指針在C中-內存分配混亂

用法:

在標題中:

#define MAX_BARS_ALLOWED 2000
extern int** Gregorian;

在cpp中:

Gregorian = read_matrix(NumLastItem+1,MAX_LINES_ALLOWED);

如果您在函數內部創建與數組名稱相同的新實例,它將覆蓋並隱藏上面的實例。 您可以分配外部數組,但不要創建具有相同名稱的新變量。

在頭文件中,對實現源有一個特殊的定義。 像這樣:

#ifndef ARRAY_HEADER_HPP
#define ARRAY_HEADER_HPP 1

#ifdef ARRAY_IMPL
#define extern // remove extern for implementation
#endif

#define MAX_LINES_ALLOWED 20000
extern int **Georgian;

#ifdef ARRAY_IMPL
#undef extern
#endif

#endif // ARRAY_HEADER_HPP

然后在分配數組的地方添加標題,如下所示

#define ARRAY_IMPL
#include "array_header.hpp"

void alloc_array(){
    Georgian = new int*[var+1];
    for(size_t n = 0; n < (var+1); n++)
        Georgian[n] = new int[MAX_LINES_ALLOWED];
}

void dealloc_array(){
    for(size_t n = 0; n < (var+1); n++)
        delete[] Georgian[n];
    delete[] Georgian;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM