C ++ /指向结构/验证成员的指针

时间:2015-08-03 13:06:00

标签: c++ validation int structure

下面是我的结构,我向用户公开,通过使用malloc给它一些大小来填充它。 使用传递给我这个结构的指针

typedef struct ServerConfiguration {
    wchar_t *IPAddress;
    USHORT PortNo;
    wchar_t *Title;
    int repeatCount;
    int timeout;
} ServerConfig;

ServerConfig *serverconfig = (ServerConfig*)malloc(sizeof(ServerConfig));
dcmServerconfig->IPAddress = L"localhost";
dcmServerconfig->Title = L"DVTK_MW_SCP";
dcmServerconfig->PortNo = 8080;

用户不分配重复计数// 它指向一些垃圾邮件地址//示例repeatCount = 380090700

我有另一个具有struct的结构,

typedef struct CommonParameters {
    //other members;
    int repeatCount
} commonParams;

我必须验证ServerCOnfig值,然后将其分配给CommonParameters,如下所示

if (serverConfig->opt_repeatCount > 1) {
    commonParams.repeatCount = serverConfig->repeatCount;
}

serverConfig->repeatCount的值如果没有被用户分配,则是一些垃圾(380090700)。在我的情况下,大于1。我需要验证此serverConfig->repeatCount是否具有有效值,然后才传递if条件
最后,我的问题是验证一个结构变量,它是一个适当值的整数。

1 个答案:

答案 0 :(得分:0)

您的代码看起来像是以非常基于C的样式编写的(即使用malloc分配一块内存,然后手动初始化struct的字段)。如果采用更常见的基于C ++的样式,使用new分配内存和构造函数来初始化字段,您会发现这些问题变得更容易。例如,在您的情况下,您可以将CommonParameters编写为:

struct CommonParameters {
    CommonParameters(int rc) :
    repeatCount(rc)
    {}

    //other members;
    int repeatCount
};

这样CommonTrarameters在创建时就被初始化了,你不必担心它的初始化状态。

注意:因为您的问题是用纯C编写的,所以您可能只是将问题误标为C ++。如果是这样,请更改标签,我会更新我的答案。

相关问题