我想动态更改结构内部数组的大小。 我有以下结构:
struct PolynomStruct {
double * term;
unsigned int size;
};
typedef struct PolynomStruct *Polynom;
当我尝试创建一个新的多项式时,我必须为该结构保留内存以使用该结构内的变量,对吗?
Polynom res = malloc(sizeof(struct PolynomStruct));
res->size = 10;
然后,我想在索引4的术语数组中添加双精度型。 因此它应该看起来像[0,0,0,0,2.0000]。 我要做的第一件事是重新分配数组的内存。
res->term = realloc(5 * sizeof(double));
我认为sizeof(res-> term)应为5 * 8字节= 40字节。 但是下面的代码返回8。
printf("size term: %lu\n",sizeof(res->term));
“尺寸项:8”
后来我尝试这样做:
res->term[4] = 2;
printf("%f\n",res->term[4] );
它将“ 2.000000”打印到标准输出。我真的不明白这是如何工作的。 如果有人可以给我提示,我将非常高兴。 对不起,我的英语。
答案 0 :(得分:2)
sizeof(res->term)
返回指针的大小,而不是分配的内存。
您需要手动跟踪分配的金额,即按res-> size * sizeof(* term)或类似的内容进行跟踪。
答案 1 :(得分:2)
首先,您不希望这样做:
Polynom res = malloc(sizeof(struct PolynomStruct));
res->size = 10;
您已为结构分配了空间,但尚未初始化所需的term
指针:
Polynom res = malloc(sizeof(struct PolynomStruct));
if(res==NULL){
//Handle allocation failure...
}
res_>term=NULL;
res->size = 0;
//Later....
free(res->term);
free(res);
这为struct
分配了空间,并将数组初始化为空。
请注意,将NULL
传递给free()
很好,它什么也不做,可以正常返回。
或者如果您确实想预分配10个字词:
Polynom res = malloc(sizeof(struct PolynomStruct));
if(res==NULL){
//Handle allocation failure...
}
res->size = 10;
res_>term=malloc(res->size*sizeof(double));
if(res->term==NULL){
res->size=0;
//Handle error...
}
//Later (when finished with res)...
free(res->term);
free(res);
这会将数组预分配为10。如果预分配,则可能要跟踪capac
(分配了多少)和size
(使用了多少)。但这超出了这里的范围。
要重新分配,请为此编写一个函数:
int reallocate(Polynom res,int newsize){
double *resized=realloc(res->term,newsize*sizeof(double));
if (resize==NULL){
//Allocation failed. The array is the same size as before.
return 1; //Or handle error your own way.
}
res->term=resized;
res->size=newsize;
//realloc may extend the space allocated in place or realloc space elsewhere.
//If it does reallocate elsewhere the current contents are just copied over
//(byte for byte) and the old space freed.
return 0;//Success. No error.
}
//Later (when finished with res)...
free(res->term);
free(res);
然后明智的做法是使用res=NULL;
以避免造成混乱。
请注意,如果指针是由malloc
或realloc
(而非NULL
)返回的,则它必须转到free()
(恰好一次)。
还请注意realloc
可以减小大小,因此newsize < res->size
可以。
答案 2 :(得分:0)
我觉得指针与数组可能有些混淆。请阅读这篇有用的文章:Are pointers and arrays equivalent in C?
您不要“更改结构内部数组的大小”,因为拥有结构的全部目的是使事情保持稳定。因此,Polynom res = malloc(sizeof(struct PolynomStruct))将始终在堆上为res分配相同数量的备忘录。
如果要构建一个双精度数组和指向其的堆数组,可以执行以下操作:
int member=10; // grow array size by member=member*2 for example
double a[]=malloc(member*sizeof(double));
term=a;
这样,您可以动态地扩展阵列。