【问题标题】:Using realloc() function in C for increasing column in 2D array在 C 中使用 realloc() 函数来增加二维数组中的列
【发布时间】:2017-03-12 10:54:38
【问题描述】:

我有以下代码必须调整二维数组矩阵列的大小:

#include <stdio.h> 
#include <stdlib.h>
int main(int argc, char * argv[]){

int n = 3;
int m = 4;
int * * mas = malloc(n * sizeof( * mas));

for (int i = 1; i < n + 1; i++) {
  mas[i] = malloc(m * sizeof( * (mas[i])));
}
for (int i = 1; i < n + 1; i++) {
  for (int j = 0; j < m; j++) {
    mas[i][j] = i + 1;
    printf("%d ", mas[i][j]);
  }
  printf("\n");
}
printf("\n");

当我调整一列矩阵的大小(但保留相同大小的行)时,它会结束循环:

for (int i = 1; i < n + 1; i++) {
  int * tmp = realloc(mas[i], (m + 1) * sizeof( * mas[i]));
  if (tmp) {
    mas[i] = tmp;
  }
}

mas[1][4] = 100;
mas[2][4] = 200;
mas[3][4] = 300;

for (int i = 1; i < n + 1; i++) {
  for (int j = 0; j < m + 1; j++) {
    printf("%d ", mas[i][j]);
  }
  printf("\n");
}
for(int i = 1; i< n+1; i++){
    free(mas[i]);
}
free(mas);
system("pause");
return 0;
}

  I have:
  2 2 2 2
  3 3 3 3
  4 4 4 4

打印完这个 myprg.exe 后

但是当我使用简单矢量调整大小时,它已经完成了!

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

int main(int argc, char * argv[]) {
int n = 3;
int m = 4;
int* mas = malloc(n*sizeof(mas));

for(int i = 1; i < n+1; i++){
    mas[i] = 0;
}
for(int i = 1; i < n+1; i++){
    printf("%d\n", mas[i]);
}
mas = realloc(mas, (n+2)*sizeof(*mas));
for(int i = 1; i < n+3; i++){
    mas[i] = 0;
}
for(int i = 1; i < n+3; i++){
     printf("%d\n", mas[i]);
}
free(mas);
system("pause");
return 0;
}

我认为这是带有二维数组指针的东西,但我不明白到底是什么:(

【问题讨论】:

  • 详细信息:int * * masint * mas 都不是指向二维数组的指针。 int (*mas)[n][m] 是一个指向二维数组的指针。

标签: c arrays matrix realloc


【解决方案1】:

将代码中的每个for (int i = 1; i &lt; n + 1; i++) 替换为for (int i = 0; i &lt; n; i++)。数组索引从 0n-1 而不是 1n

同样,改变

mas[1][4] = 100;
mas[2][4] = 200;
mas[3][4] = 300;

mas[0][4] = 100;
mas[1][4] = 200;
mas[2][4] = 300;

出于同样的原因。

最好也检查一下mallocs 的返回值,看看是否成功。此外,如果realloc 失败并且tmpNULL,您应该采取适当的措施。

【讨论】:

  • 谢谢!)它现在正在工作,但现在我有一个新的问题来完成我的大学任务,我最好在 2D 矩阵中取 1 到 3 行和 0 到 9 列。
  • 抱歉,我没听懂。也许将m 的值更改为10?如果调整大小,则为 9。
  • 哦,对不起,我没有正确表达。例如,我编写的这段代码是因为 realloc() 在我的行 - 1 到 3 和列 - 0 到 8 的劳动代码中失败。
  • 另外,你能解释一下为什么它只在从 0 开始时对 realloc 不起作用(当第 1 到第 3 行)?
  • 数组索引从零开始。同样,内存地址从零开始。为什么?我只能说,它就是这样设计的。
猜你喜欢
  • 2019-05-01
  • 2021-12-25
  • 2016-01-05
  • 2013-12-16
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
相关资源
最近更新 更多