假设我想定义一个表示向量长度及其值的结构:
struct Vector{
double* x;
int n;
};
现在,假设我要定义向量y并为其分配内存。
struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));
我在互联网上的搜索显示我应该分别为x分配内存。
y->x = (double*)malloc(10*sizeof(double));
但是,似乎我为y-> x分配了两次内存,一次为y分配内存,另一次为y-> x分配内存,这似乎浪费了内存。如果让我知道编译器的实际功能以及初始化y和y-> x的正确方法,将不胜感激。
提前致谢。
不,您不会y->x
两次分配内存。
相反,你的结构分配内存(其中包括一个指针)加东西该指针指向。
这样想:
1 2
+-----+ +------+
y------>| x------>| *x |
| n | +------+
+-----+
因此,您实际上需要两个分配(1
和2
)来存储所有内容。
另外,您的类型应该是struct Vector *y
指针,并且永远不要malloc
在C中强制转换void*
返回值,因为它可以隐藏某些您不想隐藏的问题-C完全能够将返回值隐式转换为任何其他指针。
而且,当然,您可能希望封装这些向量的创建,以使对它们的管理更加容易,例如:
struct Vector {
double *data; // no place for x and n in readable code :-)
size_t size;
};
struct Vector *newVector (size_t sz) {
// Try to allocate vector structure.
struct Vector *retVal = malloc (sizeof (struct Vector));
if (retVal == NULL)
return NULL;
// Try to allocate vector data, free structure if fail.
retVal->data = malloc (sz * sizeof (double));
if (retVal->data == NULL) {
free (retVal);
return NULL;
}
// Set size and return.
retVal->size = sz;
return retVal;
}
void delVector (struct Vector *vector) {
// Can safely assume vector is NULL or fully built.
if (vector != NULL) {
free (vector->data);
free (vector);
}
}
通过像这样封装创建的内容,可以确保矢量是完全构建的还是完全不构建的-不可能半构建向量。它还允许您将来完全更改基础数据结构,而不会影响客户端(例如,如果要使它们稀疏阵列以牺牲空间来提高速度)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句