Question about using malloc in 2d array with the the 1 dimension known in C

huangapple go评论54阅读模式
英文:

Question about using malloc in 2d array with the the 1 dimension known in C

问题

我遇到了一个具有如下形式的二维数组的程序 ps[i][j]。问题是,我知道 j 的大小是 3,但我不知道 i 的大小(这也是我想使用 malloc 和 free() 的原因)。我该如何在这样的数组中使用 malloc?因为它不是一个一维数组,而是一个二维数组,但问题是我只不知道 i 的大小。例如,这是数组的样子

ps[?][3] 

j 的大小是已知的,为 3,但 i 的大小是未知的。

谢谢你宝贵的时间,期待你的回复。

英文:

general question here.

I came across a program that has one 2d array like this ps[i][j]. The problem is that i know the size of the j which is 3 but i dont know the size of i (hence the reason i want to use malloc and free(). How can i use the malloc in an array like this? Because its not a 1d array but a 2d array but the issue is that i only dont know the size of i. For example this is the array

ps[?][3] 

. The size of j is know which is 3 but the i size is unknown.

Thank you for your precious time, i am looking forward to your replies

答案1

得分: 1

你需要声明一个指向给定大小数组的指针,即 unsigned int (*arr)[3],然后为该类型的数组的 i 个元素分配空间:

unsigned int (*arr)[3] = malloc(i * sizeof(unsigned int[3]));

更好的做法是:

unsigned int (*arr)[3] = malloc(i * sizeof *arr);

然后你可以这样释放它:

free(arr);
英文:

You need to declare a pointer to an array of the given size, i.e. unsigned int (*arr)[3], then allocate space for i elements of an array of that type:

unsigned int (*arr)[3] = malloc(i * sizeof(unsigned int[3]));

Better yet:

unsigned int (*arr)[3] = malloc(i * sizeof *arr);

Then you free it like this:

free(arr);

huangapple
  • 本文由 发表于 2023年1月8日 22:49:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定