C中动态分配数组的数组 [英] dynamic allocating array of arrays in C

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

问题描述

我并不真正了解 C 中的一些基本内容,例如动态分配数组数组.我知道你可以做到:

I don't truly understand some basic things in C like dynamically allocating array of arrays. I know you can do:

int **m;

为了声明一个二维数组(随后将使用一些 *alloc 函数进行分配).也可以通过执行 *(*(m + line) + column) 来轻松"访问它.但是我应该如何为该数组中的元素赋值?使用 gcc 以下语句 m[line][column] = 12; 因分段错误而失败.

in order to declare a 2 dimensional array (which subsequently would be allocated using some *alloc function). Also it can be "easily" accessed by doing *(*(m + line) + column). But how should I assign a value to an element from that array? Using gcc the following statement m[line][column] = 12; fails with a segmentation fault.

任何文章/文档将不胜感激.:-)

Any article/docs will be appreciated. :-)

推荐答案

m[line][column] = 12 语法没问题(提供 linecolumn 在范围内).

The m[line][column] = 12 syntax is ok (provided line and column are in range).

然而,你并没有编写你用来分配它的代码,所以很难判断它是对还是错.它应该类似于

However, you didn't write the code you use to allocate it, so it's hard to get whether it is wrong or right. It should be something along the lines of

m = (int**)malloc(nlines * sizeof(int*));

for(i = 0; i < nlines; i++)
  m[i] = (int*)malloc(ncolumns * sizeof(int));

一些旁注:

  • 这样,您可以为每一行分配不同的长度(例如三角形数组)
  • 您可以稍后在使用数组时重新分配()或释放()单个行
  • 当你 free() 整个数组时,你必须 free() 每一行

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

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