分配一个二维数组在C中与一维固定 [英] Allocate a 2d array in C with one dimension fixed
问题描述
我要动态分配一个二维数组的1维(其它尺寸给出)。这是否工作:
INT NCOLS = 20;
// NROWS =用户输入...
双* ARR [NCOLS]
ARR =(双*)malloc的(的sizeof(双)* NROWS);
和释放它:
免费(ARR)
不太 - 你声明的是一个指针数组。你想要一个指向数组的指针,这将是这样声明:
双(* ARR)NCOLS]
然后,你会分配它像这样:
ARR =的malloc(NROWS * sizeof的(双[NCOLS]));
然后可通过 NCOLS
二维数组当作一个正常的 NROWS
。要释放它,只是把它传递给免费
像任何其他的指针。
在C,有没有必要投的malloc
,因为有隐式转换从的返回值的void *
到任何指针类型(这是不是在C ++如此)。其实,这样做可以掩盖错误,如未能的#include< stdlib.h中>
,由于隐式声明的存在,因此它气馁。
数据类型双击[20]
是数组20双
,并键入双(*)[20]
是指针数组20 双
,其中 CDECL(1)
程序是能够破译复杂的C声明非常有用(的例如)。
I want to dynamically allocate 1 dimension of a 2D array (the other dimension is given). Does this work:
int NCOLS = 20;
// nrows = user input...
double *arr[NCOLS];
arr = (double *)malloc(sizeof(double)*nrows);
and to free it:
free(arr)
Not quite -- what you've declared is an array of pointers. You want a pointer to an array, which would be declared like this:
double (*arr)[NCOLS];
Then, you'd allocate it like so:
arr = malloc(nrows * sizeof(double[NCOLS]));
It can then be treated as a normal nrows
by NCOLS
2D array. To free it, just pass it to free
like any other pointer.
In C, there's no need to cast the return value of malloc
, since there's an implicit cast from void*
to any pointer type (this is not true in C++). In fact, doing so can mask errors, such as failing to #include <stdlib.h>
, due to the existence of implicit declarations, so it's discouraged.
The data type double[20]
is "array 20 of double
, and the type double (*)[20]
is "pointer to array 20 of double
". The cdecl(1)
program is very helpful in being able to decipher complex C declarations (example).
这篇关于分配一个二维数组在C中与一维固定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!