我有一段这样的代码,我想为两个维结构数组分配内存。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
struct complex
{
int re;
int im;
};
int main ()
{
int r = 5; //rows
int c = 6; //cols
struct complex (*wsk)[c];
wsk = (struct complex(*)[c])malloc(sizeof(struct complex)*r*c);
/* ... */
}
我不确定 malloc()
部分是否正确?
最佳答案
这是一种常见的方法。当所有行都具有相同数量的列时,我发现这是最好的,所以在大多数情况下。原因:
malloc
很慢。尽可能少地使用malloc
-s- 您始终需要
free
wsk
和wsk[0]
。当您更改r
和c
运行时时,这非常有用:您不必存储旧值来释放适当数量的行。
此外,不要忘记检查 malloc
是否返回了 NULL
。
struct complex ** wsk = (struct complex **) malloc(r * sizeof(struct complex*));
wsk[0] = (struct complex *) malloc(r * c * sizeof(struct complex));
int i;
for(i = 1; i < r; ++i)
wsk[i] = wsk[0] + i * c;
哦,你为什么不对结构进行 typedef?
typedef struct complex complex;
或者更简单,在声明处:
typedef struct /*complex*/ {
...
} complex;
那你就不用一直写struct complex
了,complex
就行了。
关于C malloc 二维结构数组(带行和列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32171787/