【问题标题】:Trying to malloc a typedef 2d array试图 malloc 一个 typedef 二维数组
【发布时间】:2022-01-13 00:38:41
【问题描述】:

我已经声明了一个 typedef:

typedef float Matrix[3][3];

我现在正在尝试为该数组分配内存:

Matrix* matPtr = malloc(sizeof(Matrix));

if (matPtr != NULL)
{
    for (int r = 0; r < 3; r++)
    {
        for (int c = 0; c < 3; c++)
        {
            *matPtr[r][c] = 0; 
        }
    }
}

但我得到了错误:

严重性代码描述项目文件行抑制状态 警告 C6200 索引“2”超出了非堆栈缓冲区“matPtr”的有效索引范围“0”到“0”。

我做错了什么?

【问题讨论】:

  • *matPtr[r][c] --> (*matPtr)[r][c] 。下标运算符[ ] 比解引用运算符* 具有更高的precedence。在没有括号区别的情况下应用于相同表达式中的相同 id 会受到伤害。
  • 或者float (*matPtr)[3] = malloc(sizeof(Matrix));,然后你可以使用matPtr[r][c] = 0;,不用担心缺少括号。
  • 澄清一下,声明Matrix *matPtr = malloc(sizeof(Matrix)); 等价于像float mat[1][3][3] 这样的数组声明。这意味着访问数组元素需要(*matPtr)[r][c]=0 或matPtr[0][r][c]=0。 malloc(sizeof(Matrix)) 的正确指针类型实际上是float (*matPtr)[3],它允许您使用matPtr[r][c]=0 访问数组元素

标签: c multidimensional-array memory-management


【解决方案1】:
  1. 不要将数组和指针隐藏在 typedef 后面。这是一种非常非常糟糕的做法。
  2. 使用指向数组的指针
int (*matrix)[3] = malloc(3 * sizeof(*matrix));

并用作普通矩阵

matrix[1][2] = 5;

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 2016-08-21
    • 1970-01-01
    • 2013-07-20
    • 2020-01-18
    • 1970-01-01
    • 2010-11-17
    • 2013-06-27
    • 2013-11-30
    相关资源
    最近更新 更多