分配的二维数组用C [英] Allocating 2-D array in C

查看:132
本文介绍了分配的二维数组用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时分配在C 2-D数组。现在此所用的常规方式这样来实现:

I want to allocate a 2-D array in C at runtime. Now this can be achieved in the conventional manner like this:

int *matrix[rows]
for (row = 0; row < rows; ++row) {
  matrix[row] = (int *)malloc(ncol*sizeof(int));
}

但我发现了另一个方法,做同样的事情:

But I found another method, which does the same thing:

int (*p)[rows];
p=(int (*)[rows])malloc(rows*cols*sizeof(int));

谁能解释第二个声明是如何工作的?具体来说,什么是的意思(INT(*)[行])的malloc ?据我所知,的malloc 用于像为(int *)malloc的(NCOL *的sizeof(INT))(字符*)malloc的(NCOL *的sizeof(char)的)

Can anyone explain how the 2nd declaration works? Specifically, what is meant by (int (*)[rows])malloc? To the best of my knowledge, malloc is used like (int *)malloc(ncol*sizeof(int)) or (char *)malloc(ncol*sizeof(char)).

推荐答案

在这里,你投的malloc 的返回值的类型的指针数组 INT >

Here, you cast malloc's return value to the type pointer to array rows of int.

顺便说一句,在C,指针的强制转换为无效的指针对象没有该电源线,甚至是无用的。你不应该担心这些细节。下面code工作确实也是如此。

By the way, in C, the cast of a pointer to void to a pointer to object is not requiered, and even useless. You should not worry about these details. The following code works indeed as well.

#include <stdlib.h>

int (*p)[rows];
p = malloc(rows * cols * sizeof(int));

这篇关于分配的二维数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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