Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将连续内存分配给2d数组post声明_C_Arrays_Malloc - Fatal编程技术网

C 将连续内存分配给2d数组post声明

C 将连续内存分配给2d数组post声明,c,arrays,malloc,C,Arrays,Malloc,据我所知,现代C标准允许我将一块内存分配给2d数组,如下所示: size_t rows, cols; // assign rows and cols int (*arr)[cols] = malloc(sizeof(double[cols][rows])); 但是,有没有一种方法可以在声明后将内存块分配给2d数组?例如,我在其他地方声明了一个外部变量,我想将内存分配给: size_t rows, cols; extern int **arr; //Malloc block to 2d arr

据我所知,现代C标准允许我将一块内存分配给2d数组,如下所示:

size_t rows, cols;
// assign rows and cols
int (*arr)[cols] = malloc(sizeof(double[cols][rows]));
但是,有没有一种方法可以在声明后将内存块分配给2d数组?例如,我在其他地方声明了一个外部变量,我想将内存分配给:

size_t rows, cols;
extern int **arr;

//Malloc block to 2d array
例如,我知道可以用一个索引代替2 [i] [j]->[i*行+j]
但我想知道是否可以保留这两个索引?

同时保护指针及其指向的区域

像这样

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

int **arr;

int **Malloc_block_to_2d_array(size_t rows, size_t cols){
    int **arr = malloc(rows * sizeof(*arr) + rows * cols * sizeof(**arr));
    if(arr){
        char *body_top = (char*)arr + rows * sizeof(*arr);
        for(size_t r = 0; r < rows; ++r){
            arr[r] = (int *)(body_top + r * cols * sizeof(**arr));
        }
    }
    return arr;
}

int main(void){
    //DEMO
    size_t rows = 3;
    size_t cols = 5;

    arr = Malloc_block_to_2d_array(rows, cols);
    for(size_t r = 0; r < rows; ++r)
        for(size_t c = 0; c < cols; ++c)
            arr[r][c] = (r+1)*10 + c+1;

    for(size_t r = 0; r < rows; ++r){
        for(size_t c = 0; c < cols; ++c)
            printf("%d ", arr[r][c]);
        puts("");
    }
    free(arr);
}
#包括
#包括
int**arr;
int**Malloc\u块到二维数组(大小行、大小列){
int**arr=malloc(行*sizeof(*arr)+行*cols*sizeof(**arr));
如果(arr){
char*body_top=(char*)arr+行*sizeof(*arr);
对于(大小r=0;r
您不能“保留”两个索引,因为
extern int**arr
不声明连续的2D数组。它是一个指针数组,因此编译器使用的向其应用两个索引的机制与用于2D数组的机制非常不同

最大的区别是,访问2D数组需要编译器知道
cols
的值,而访问指针数组则不需要

宣言

int (*arr)[cols] = malloc(sizeof(double[cols][rows]));
是一个可变长度数组。这在静态上下文中是不允许的,因此
arr
不能是全局的

您可以将指针数组制作成连续块。两个索引表达式将起作用,代价是分配额外的数组:

// In the header
extern size_t rows, cols;
extern double **arr;

// In the C file

size_t rows, cols;
double **arr;

void init_array(size_t r, size_t c) {
    rows = r;
    cols = c;
    double (*a)[cols] = malloc(sizeof(double[cols][rows]));
    arr = malloc(rows*sizeof(double*));
    for (size_t i = 0 ; i != rows ; i++) {
        arr[i] = a[i];
    }
}
void free_array() {
    free(arr[0]);
    free(arr);
}

这是过去同一网站上的帖子