在 C 中分配一个二维数组,一维固定 [英] Allocate a 2d array in C with one dimension fixed

查看:45
本文介绍了在 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);

并释放它:

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]));

然后它可以被 NCOLS 视为一个普通的 nrows 二维数组.要释放它,只需像任何其他指针一样将它传递给 free.

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.

在 C 中,不需要转换 malloc 的返回值,因为存在从 void* 到任何指针类型的隐式转换(这在 C++ 中不正确)).事实上,这样做可以掩盖错误,例如未能#include ,由于隐式声明的存在,所以不鼓励.

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.

数据类型double[20]double的第20个数组,double(*)[20]的类型是"指向 double" 数组 20 的指针.cdecl(1) 程序非常有助于破译复杂的 C 声明(示例).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆