【问题标题】:Defining 2D irregular array with malloc用 malloc 定义二维不规则数组
【发布时间】:2014-02-16 05:54:29
【问题描述】:

我有这个练习题:

用整数的 malloc 定义一个二维不规则数组,其中 out dim = 4 并且 inner = 10,11,12,13。 (提示:使用 for 循环)

所以,我意识到我可以用这样的整数的 malloc 编写一个 2D 不规则数组:

int (*array)[20] = malloc((sizeof *array) * 10);

那将是一个 10x20 的数组,我相信使用 amlloc。

我只是不确定如何使用 for 循环将内部尺寸从 10 更改为 11 再从 12 更改为 13。感谢任何帮助!

int j;

for (int k = 0; k < 4; k++ )
{
    for ( j = 10; j < 14; j++ )
    {
        int (*array)[4] = malloc((sizeof *array) * j)
    }
}

顺便说一句,这接近正确吗?

【问题讨论】:

  • 每次执行外部for循环时,内部for循环的结束值加1。
  • 我添加的内容接近正确吗?
  • 是的,您只需要在第二个 for 中添加类似 j &lt; 10 + k 的内容。看看它是如何工作的?
  • 由于某种原因,我在 malloc 下遇到错误。它说 void 类型的值不能用于初始化 int "int(*)[4]" 类型的实体
  • 在您做出我建议的更改之前它是否有效?

标签: arrays malloc heap-memory


【解决方案1】:

这有帮助吗? 如果有,请编辑http://en.wikibooks.org/wiki/C_Programming/Common_practices#Dynamic_multidimensional_arrays,方便下一位同学理解。

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

const int rows = 20;

int main(void) {
    int **some_data;
    // first, allocate a (column) Iliffe vector.
    some_data = malloc( (sizeof(*some_data)) * rows);
    int i=0;
    for(i = 0; i < rows; i++){
        // next, allocate each row.
        // For no good reason, make each row a different size.
        int columns = i+10;
        some_data[i] = malloc( (sizeof(**some_data)) * columns);
    };
    some_data[3][13] = 9;
    printf( "%d\n", some_data[3][13]);
    return 0;
}

如果您是通过现在似乎莫名其妙流行的锁定系统之一查看此内容,您可能会发现在一些在线 C 编译器中运行上述代码很方便,例如 http://ideone.com/http://codepad.org/ 或 @ 987654324@.

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2015-10-27
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多