我想创建一个函数来重新分配 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);
}
}
名为Parameters
的typedef 结构包含int typenum
、int typetotal
以及应通过realloc( )
。
当我尝试编译时,在 Tiny C (Windows) 中出现错误:*文件在 C 中。
错误:无法将“struct parameters”转换为“void *”
(这见于 'p[i] = realloc(p[i],sizeof(Parameters) * typetotal')
谁能帮我重写这个函数,以便我能够在 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()
和 realloc()
的返回值。
至于为什么,看这个reference
关于从 realloc() 函数创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19119729/