Pou*_*uya 70 c memory-management
假设我想定义一个表示向量长度的结构及其值,如下所示:
struct Vector{
double* x;
int n;
};
Run Code Online (Sandbox Code Playgroud)
现在,假设我想定义一个向量y并为其分配内存.
struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));
Run Code Online (Sandbox Code Playgroud)
我在互联网上的搜索显示我应该分别为x分配内存.
y->x = (double*)malloc(10*sizeof(double));
Run Code Online (Sandbox Code Playgroud)
但是,似乎我为y-> x分配内存两次,一次为y分配内存,另一种为y-> x分配内存,这似乎浪费了内存.如果让我知道编译器真正做了什么以及初始化y和y-> x的正确方法,我们非常感激.
提前致谢.
pax*_*blo 133
不,你不是y->x两次分配内存.
相反,你的结构分配内存(其中包括一个指针)加东西该指针指向.
想一想:
1 2
+-----+ +------+
y------>| x------>| *x |
| n | +------+
+-----+
Run Code Online (Sandbox Code Playgroud)
所以你实际上需要两个分配(1和2)来存储一切.
另外,你的类型应该是struct Vector *y因为它是一个指针,你不应该从mallocC中转换返回值,因为它可以隐藏你不想隐藏的某些问题 - C完全能够隐式地将void*返回值转换为任何其他指针.
当然,您可能希望封装这些向量的创建,以便更轻松地管理它们,例如:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
通过封装这样的创建,您可以确保向量完全构建或根本不构建 - 它们不可能是半构建的.它还允许您在不影响客户端的情况下完全更改底层数据结构(例如,如果您希望使它们稀疏数组以换取空间以获得速度).