我想创建一个将重新分配2D数组的函数 typedef struct
typedef struct hero_data{
char name[254];
char title[254];
int encoding;
int startstr;
double incstr;
int startdex;
double incdex;
int startintel;
double incintel;
int basemindmg,basemaxdmg;
double bat;
double basearmor;
struct hero_data *next;
struct hero_data *Class;
}hero;
typedef struct parameters{
int toughtotal;
int nimbletotal;
int smarttotal;
int skeptictotal;
int mystictotal;
int cursedtotal;
int brutetotal;
int shreddertotal;
int vanillatotal;
int typetotal;
int typenum;
hero **smart[];
hero **nimble[];
hero **tough[];
hero **type[][];
hero **skeptic[][];
hero **mystic[][];
hero **cursed[][];
hero **brute[][];
hero **shredder[][];
hero **vanilla[][];
}Parameters;
void reallocation(Parameters *p, int typenum,int typetotal)
{
int i;
p = realloc(p,sizeof(Parameters *) * typenum);
for ( i = 0; i < typenum; i++)
{
p[i] = realloc(p[i],sizeof(Parameters) * typetotal);
}
}
上面的函数应按如下方式调用: void reallocation(p->type,p->typenum,p->typetotal);
因此,通过正确替换函数的参数,我希望函数看起来像:
void reallocation(Parameters *p, int typenum,int typetotal)
{
int i;
p->type = realloc(p->type,sizeof(Parameters *) * p->typenum);
for ( i = 0; i < p->typenum; i++)
{
p->type[i] = realloc(p->type[i],sizeof(Parameters) * p->typetotal);
}
}
名为的typedef结构Parameters
包含int typenum
,int typetotal
和应该通过初始化的2D数组realloc()
。
尝试编译时,在Tiny C(Windows)中出现错误:*文件在C中。
错误:无法将“结构参数”强制转换为“无效*”
(这在'p [i] = realloc(p [i],sizeof(Parameters)* typetotal'中出现))
谁能帮助我重写此函数,以便我可以在内重新分配2D数组Parameter *p
?
我尝试将其更改void reallocation(Parameters *p, ...)
为void reallocation(Parameters *p[], ...)
,错误#2变成了与错误#1相同的消息,并且出现在的=
中p[i] = realloc (...);
代码的一个大问题是,您要相互分配不相等的类型,并且您也没有检查的结果realloc
。如果此调用失败,则将泄漏最初分配的内存。
假设你的结构看起来像
typedef struct {
int typenum;
int typetotal;
} Parameters;
Parameters *p;
p = malloc(10 * sizeof(*p));
if (p == NULL)
printf("Allocatation of memory failed!\n");
要适当地重新分配以说20,您可以执行以下操作
reallocate_p(&p, 20);
该函数定义为
void reallocate_p(Parameters **p, int new_size)
{
Parameters *temp;
temp = realloc(*p, sizeof(*temp) * new_size);
if (temp==NULL) {
printf("Reallocatation of memory failed!\n");
// Handle error
}
*p = temp;
return;
}
另请注意,我们不会强制转换malloc()
and的返回值realloc()
。至于为什么,请参阅此参考
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句