【问题标题】:dynamic allocation of matrix动态分配矩阵
【发布时间】:2021-10-13 08:46:44
【问题描述】:

这个函数应该分配一个 1 行 2 列的矩阵 ('resMat')。

由于某种原因,我在“resMat”中得到的只是 1 行,1 列。

知道为什么吗? 谢谢。

void Ex2()
{
    int** resMat = NULL;
    int rows = 1;
    int* cols = (int*)calloc(rows, sizeof(int*));
    cols = {2};
    int i;
    resMat = (int**)calloc(rows, sizeof(int*));
    assert(resMat);
    for (i = 0; i < rows; i++)
    {
        resMat[i] = (int*)calloc(cols[i], sizeof(int)); // cols[i]=cols[0]=2
        assert(resMat[i]);
    }   

我稍微更改了代码以使其更具可读性。 'rows' 和 'cols' 实际上是由其他函数定义的,这就是为什么 'cols' 是一个数组(如果 rows>1)

【问题讨论】:

  • 如果您的目标是 C(您的问题被标记为 C),请不要转换 calloc 的结果,因为这会隐藏问题:stackoverflow.com/questions/605845/…
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange (SE) 网络上发帖,您已在 CC BY-SA license 下授予 SE 分发内容的不可撤销权利(即无论您未来的选择如何)。根据 SE 政策,分发非破坏版本。因此,任何破坏行为都将被撤销。请参阅:How does deleting work? …。如果允许删除,则帖子下方左侧有一个“删除”按钮,但仅在浏览器中,而不是移动应用程序中。

标签: c pointers matrix dynamic-memory-allocation


【解决方案1】:

这些陈述

int* cols = (int*)calloc(rows, sizeof(int*));
cols = {2};

使用这个 for 循环会产生内存泄漏(起初,指针 cols 用分配的内存地址初始化,然后由整数常量 2 重新分配;因此分配的内存地址丢失)

for (i = 0; i < rows; i++)
{
    resMat[i] = (int*)calloc(cols[i], sizeof(int)); // cols[i]=cols[0]=2
    assert(resMat[i]);
}   

没有意义。

在for循环内的这个语句中

resMat[i] = (int*)calloc(cols[i], sizeof(int));

使用了指针cols,其值为2,被取消引用 在表达式 cols[i] 中导致未定义的行为

你所需要的就是以下

int cols = 2;

resMat = calloc(rows, sizeof(int*));
assert(resMat);
for ( i = 0; i < rows; i++)
{
    resMat[i] = calloc( cols, sizeof( int ));
    assert(resMat[i]);
} 

【讨论】:

  • 使用assert 作为一种检测内存分配失败的方法是不好的做法。它是一个可以实现为 NO-OP 的宏。如果断言失败,它可能会调用abort,这又可能导致核心转储。一般来说,assert 是一个有用的宏,用于检测开发人员违反某些 API 合同的编程错误。但它对于检测和通知程序外部的错误没有用。为此使用if(...) { perror("..."); ... } 或类似名称。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 2021-12-19
  • 2014-03-25
  • 2010-11-27
  • 2015-10-14
  • 2015-11-10
  • 1970-01-01
  • 2011-07-07
相关资源
最近更新 更多