如何释放矩阵的某些行和列

时间:2022-07-20 04:36:33

So I have a matrix which was created this way :

所以我有一个以这种方式创建的矩阵:

 int **mat(int nl, int nc) {
  int i;
  int **v = malloc(nl * sizeof(int *));

  for (i = 0; i < nl; i++) {
    v[i] = calloc(nc, sizeof(int));
  }
  return v;
}

Let's say after the input , it is :

让我们说输入后,它是:

0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7

I would want to keep only the first 2 rows and first 3 columns , and free the memory of the other rows and columns , so it would look like :

我想只保留前2行和前3列,并释放其他行和列的内存,所以它看起来像:

0 1 2
1 2 3

How do I do that ?

我怎么做 ?

1 个解决方案

#1


2  

you would have to:

你必须:

  • free the full rows after the 2 first ones (and set nl to 2):
  • 在2个第一个之后释放完整行(并将nl设置为2):

like this:

喜欢这个:

for (i = 2; i < nl; i++) {
    free(v[i]);
  }
nl = 2;
  • perform a realloc of the remaining rows (set nc to 3 as well)
  • 执行剩余行的重新分配(将nc设置为3)
  • check realloc return code. In the unlikely case it would return NULL, fallback to keeping your old array (reference)
  • 检查realloc返回码。在不太可能的情况下,它将返回NULL,回退以保持您的旧数组(引用)

like this:

喜欢这个:

  nc = 3;
  for (i = 0; i < nl; i++) {
    int *new_v = realloc(v[i], nc*sizeof(int));
    if (new_v!=NULL)
    {
       v[i] = new_v;
    }
  }

Edit: if you didn't change nc and print the "old" values, it would appear to have done nothing because the old values could be still there (freeing does not mean resetting the memory), but you may access unallocated data now: performing another allocation can reuse the freed data and overwrite it.

编辑:如果您没有更改nc并打印“旧”值,它似乎什么也没做,因为旧值可能仍然存在(释放并不意味着重置内存),但您现在可以访问未分配的数据:执行另一个分配可以重用已释放的数据并覆盖它。

#1


2  

you would have to:

你必须:

  • free the full rows after the 2 first ones (and set nl to 2):
  • 在2个第一个之后释放完整行(并将nl设置为2):

like this:

喜欢这个:

for (i = 2; i < nl; i++) {
    free(v[i]);
  }
nl = 2;
  • perform a realloc of the remaining rows (set nc to 3 as well)
  • 执行剩余行的重新分配(将nc设置为3)
  • check realloc return code. In the unlikely case it would return NULL, fallback to keeping your old array (reference)
  • 检查realloc返回码。在不太可能的情况下,它将返回NULL,回退以保持您的旧数组(引用)

like this:

喜欢这个:

  nc = 3;
  for (i = 0; i < nl; i++) {
    int *new_v = realloc(v[i], nc*sizeof(int));
    if (new_v!=NULL)
    {
       v[i] = new_v;
    }
  }

Edit: if you didn't change nc and print the "old" values, it would appear to have done nothing because the old values could be still there (freeing does not mean resetting the memory), but you may access unallocated data now: performing another allocation can reuse the freed data and overwrite it.

编辑:如果您没有更改nc并打印“旧”值,它似乎什么也没做,因为旧值可能仍然存在(释放并不意味着重置内存),但您现在可以访问未分配的数据:执行另一个分配可以重用已释放的数据并覆盖它。