简体   繁体   English

包含动态数组的不透明c结构

[英]opaque c struct containing dynamic arrays

Is this the correct way to allocate memory for ac struct that contains a dynamic array? 这是为包含动态数组的结构分配内存的正确方法吗? In particular, is the way I allocate memory for myStruct correct, considering that it is not yet known how big the struct actually is? 特别是,考虑到尚不知道结构的实际大小,我为myStruct分配内存的方式是否正确?

//test.h
struct Test;
struct Test * testCreate();
void testDestroy(struct Test *);
void testSet(struct Test *, int);

//test.c
#include <stdlib.h>
struct Test{
  double *var;
};

struct Test * testCreate(int size){
  struct Test *myTest = (struct Test *) malloc(sizeof(struct Test));
  myTest->var = malloc(sizeof(double)*size);
  return(myTest);
}
void testDestroy(struct Test * myTest){
  free(myTest->var);
  free(myTest);
}
void testSet(struct Test * myTest, int size){
  int i;
  for (i=0;i<size;++i){
    myTest->var[i] = i;
  }
}

struct s have fixed size, and that's what sizeof returns. struct具有固定的大小,这就是sizeof返回的内容。

Your struct has on element, a double pointer, and that has a (platform dependent) fixed size. 您的结构具有on元素,双指针,并且具有(与平台有关的)固定大小。

Your testCreate function does things correctly. 您的testCreate函数可以正确执行操作。 In case you don't know the size of the dynamically allocated part, you can set the pointer to NULL to denote that the memory has to be allocated later. 如果您不知道动态分配的部分的大小,可以将指针设置为NULL以表示必须稍后分配内存。

Yes, you correctly malloc space for the struct and then space for the array of doubles in the struct. 是的,您正确地为该结构分配了空间,然后为该结构中的双精度数组分配了空间。 As a practical matter, you should always test the return from malloc() for NULL before attempting to use the memory. 实际上,在尝试使用内存之前,应始终测试malloc()的返回是否为NULL。 Also, most programs like this store the size of the array in the struct as well so you can write more general code that ensures it doesn't run off the end of the allocated space. 同样,大多数类似这样的程序也将数组的大小存储在结构中,因此您可以编写更通用的代码以确保它不会在分配的空间的末尾运行。

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

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