【发布时间】:2021-10-12 23:13:20
【问题描述】:
前几天我在写代码,做一些向量数学。那使用动态分配的结构成员。初始化此类结构实例的代码必须以某种方式知道实例是否已经初始化。
我使用了以下方法...
文件 vector.h 包括...
文件:“vector.h”
#include<stdint.h>
#include"complex.h" // struct cplx defined here
#define SET 0x00
#define UNSET 0x01
struct vector {
struct cplx *res; // for resolution vectors
uint8_t status;
uint8_t dim; // dimension of vector
};
typedef struct vector Vector;
void setvector(Vector *vec,int _dim,...);
//ellipsis contains pairs of double values representing the complex magnitude of each resolution vector in order.
和文件 "setvector.c" ...
#include<stdarg.h>
#include"vector.h"
#include<limits.h>
#include<stdlib.h>
void setvector (Vector *vec,int _dim,...)
{
if(vec->status != SET){
vec->res = calloc(vec->dim = (uint8_t)_dim, sizeof(*vec->res));
vec->status = SET;
}
va_list dptr;
va_start (dptr, _dim);
/*blah..blah..blah........
.....some code......*/
//To modify already set vectors
vec->res = realloc(vec->res,(vec->dim = (uint8_t)_dim) * sizeof(*vec->res));
/*..blah...*/
va_end(dptr);
}
假设一个向量对象的实例在某个函数(例如main)中本地(运行时)初始化,那么它们的结构成员status应该包含“垃圾值”的可能性很小在初始化时,与宏 SET 具有相同的值。预先确定,对于uint8_t 类型,假设所有值的概率相等,那么这个“垃圾值”等于SET 的机会恰好是256 中的一个即1/256。这意味着例程 setvector 将失败 - 通过调用 realloc 而不调用 calloc - 每 256 次调用至少 一次。 (这将导致程序随机失败并出现segmentation fault 错误,原因不明)。可以通过将 status 设置为 4 字节 int 为 once 每 2^32 调用来减少这种机会,但这只是在逃避问题,而不是解决问题。
有没有办法在 C 中创建例程来初始化结构实例而不会出现这个问题。 例如,通过为结构成员设置默认值?
提前致谢 :-)。
我知道这个问题可以通过使用 C++ 结构及其构造函数来解决。(我认为 C++ 结构支持默认值,但我不确定)。
但我正试图用 C 来做。
【问题讨论】:
-
你如何动态分配你的向量?如果使用
malloc,则考虑calloc,而不是......将所有分配的内存设置为零,因此您知道status的初始值将是0。 -
将 res 初始化为 NULL。
-
我应该在问题(我的错)中更清楚地说明这一点。我试图使函数
setvector为用户在初始化Vector时的疏忽做好准备。基本上,我试图通过“隐藏”结构的实际工作来在 c 中实现类似 c++ 的功能。 -
@Adrian Mole,感谢您让我了解这一点。我不意识到
calloc的这种行为。