简体   繁体   English

如何在结构内部重新分配double数组

[英]how to realloc an array of double inside a struct

I would like to dynamically change the size of an array inside a struct. 我想动态更改结构内部数组的大小。 I got the following structure: 我得到以下结构:

struct PolynomStruct {
  double * term;
  unsigned int size;
};

typedef struct PolynomStruct *Polynom;

When I try to create a new Polynom I have to reserve memory for the struct to use the variables inside the struct, right?: 当我尝试创建一个新的多项式时,我必须为该结构保留内存以使用该结构内的变量,对吗?

Polynom res = malloc(sizeof(struct PolynomStruct));
res->size = 10;

Afterwards I want to add a double to the term array at index 4. So it shall look like this [0,0,0,0,2.0000]. 之后,我想在索引4处为术语数组添加一个双精度。因此,它看起来应该像[0,0,0,0,2.0000]。 The first thing I do is to reallocate the memory of the array. 我要做的第一件事是重新分配数组的内存。

  res->term = realloc(5 * sizeof(double));

In my opinion the sizeof(res->term) should be 5 * 8 bytes = 40 bytes. 我认为sizeof(res-> term)应该是5 * 8字节= 40字节。 But the following code returns 8. 但是以下代码返回8。

printf("size term: %lu\n",sizeof(res->term));

"size term: 8" “大小:8”

Afterwards I tried to do this: 之后,我尝试这样做:

res->term[4] = 2;
printf("%f\n",res->term[4] );

It prints "2.000000" to stdout. 它将“ 2.000000”打印到标准输出。 I really dont get how this works. 我真的不明白这是如何工作的。 I would be very happy if someone could give me a hint. 如果有人可以给我提示,我将非常高兴。 Sorry for my English. 对不起我的英语不好。

sizeof(res->term) returns size of the pointer, not of the allocated memory. sizeof(res->term)返回指针的大小,而不是分配的内存的大小。 You need to track manually the allocated amount, ie by res->size * sizeof(*term) or something similar. 您需要手动跟踪分配的数量,即通过res-> size * sizeof(* term)或类似的方法。

First you don't want this: 首先,您不希望这样:

Polynom res = malloc(sizeof(struct PolynomStruct));
res->size = 10;

You've allocated space for the struct but not initialised the term pointer you want: 您已为结构分配了空间,但尚未初始化所需的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);

That allocates space for the struct and initialises the array as empty. 这为struct分配了空间,并将数组初始化为空。 Notice it's fine to pass NULL to free() it does nothing and returns normally. 请注意,将NULL传递给free()可以的,它不执行任何操作并正常返回。

Or if you did want to preallocate 10 terms: 或者,如果您确实要预分配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);

That preallocates the array to being 10. If you preallocate you may want to track a capac (how much is allocated) and size (how much is used). 这会将数组预先分配为10。如果预先分配,则可能要跟踪capac (分配了多少)和size (使用了多少)。 But that's beyond the scope here. 但这超出了这里的范围。

To reallocate write a function ike this: 要重新分配,请像下面这样编写一个函数:

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);

It's often wise to then res=NULL; 然后, res=NULL;通常是明智的res=NULL; to avoid confusing mishaps. 避免造成混乱。

Notice if a pointer was returned by malloc or realloc (and not NULL ) it must go to free() (exactly once). 注意,如果指针是由mallocrealloc返回的(不是NULL ),则它必须转到free() (恰好一次)。

Also notice realloc can reduce the size so newsize < res->size is fine. 还要注意realloc可以减小大小,因此newsize < res->size很好。

I feel there might be some confusion over pointer vs array. 我觉得指针与数组可能有些混淆。 Please read this helpful article: Are pointers and arrays equivalent in C? 请阅读这篇有用的文章: 指针和数组在C中是否等效?

You don't "change the size of an array inside a struct" because the whole point of having a struct is keeping things stable. 您不要“更改结构内部数组的大小”,因为拥有结构的全部目的是使事情保持稳定。 Therefore, Polynom res = malloc(sizeof(struct PolynomStruct)) will always allocate the same amount of memo on the heap for res. 因此,Polynom res = malloc(sizeof(struct PolynomStruct))将始终在堆上为res分配相同数量的备忘录。

If you want to build a heap array of doubles and points term to it, you can do: 如果要构建双精度数组和指向其的堆数组,则可以执行以下操作:

int member=10; // grow array size by member=member*2 for example
double a[]=malloc(member*sizeof(double));
term=a; 

This way, you can dynamically grow your array. 这样,您可以动态增长阵列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM