【问题标题】:How to work out if a member of a struct was set or not?如何确定结构的成员是否已设置?
【发布时间】:2019-12-31 17:51:56
【问题描述】:

假设我有以下结构:

struct cube {  
    int height;
    int length;
    int width;
};

我需要创建一个库,允许用户将值输入到结构中,然后将其传递给函数,该函数将确定用户是否需要提供的值中的 areavolume

例如:

int main() {
    struct cube shape;

    shape.height = 2;
    shape.width = 3;

    printf("Area: %d", calculate(shape)); // Prints 6

    shape.length = 4;
    printf("Volume: %d", calculate(shape)); // Prints 24

    return 0;
}

int calculate(struct cube nums) {
    if (is_present(nums.height, nums) && is_present(nums.width, nums)) {
        return nums.height * nums.width;
    }

    else if (is_present(nums.height, nums) && is_present(nums.width, nums) && is_present(nums.length, nums)) {
        return nums.height * nums.width * nums.length;
    }
    else {
        return -1; // Error
    }
}

如果我可以使用一个函数(例如我刚刚编造的is_present())来确定一个值是否被赋予了一个结构的成员,这应该可以工作。

有没有这样的功能,如果没有,怎么实现?

【问题讨论】:

  • 没有,你必须做一些事情,比如给高度/长度/宽度-1,然后测试它(代替你的 is_present 函数)。或者你可以做一个不透明的结构并有一个 get/set 函数。这样你就知道了。
  • 为什么允许cube 的无效实例存在?为什么不通过在创建它之前检查缺失的字段来避免这个问题?

标签: c function struct variable-assignment standard-library


【解决方案1】:

您应该将您的字段初始化为可能值域之外的内容。例如,对于此类为正数的维度,负值可以充当“未分配”值。

另外,我重新排序了您的 if 语句:检查所有字段的应该是第一个。

这是一个例子:

#include <stdio.h>

#define NOT_PRESENT -1
#define is_present(x) ((x) != NOT_PRESENT)

struct cube {  
    int height;
    int length;
    int width;
};

int calculate(struct cube);

int main() {
    struct cube shape = {
        .height = NOT_PRESENT,
        .length = NOT_PRESENT,
        .width = NOT_PRESENT,
    };

    shape.height = 2;
    shape.width = 3;

    printf("Area: %d\n", calculate(shape)); // Prints 6

    shape.length = 4;
    printf("Volume: %d\n", calculate(shape)); // Prints 24

    return 0;
}

int calculate(struct cube nums) {
    if (is_present(nums.height) && is_present(nums.width) && is_present(nums.length)) {
        return nums.height * nums.width * nums.length;
    } else if (is_present(nums.height) && is_present(nums.width)) {
        return nums.height * nums.width;
    } else {
        return -1; // Error
    }
}

【讨论】:

    【解决方案2】:

    首先,您必须明确定义“a value was given”对您的域意味着什么。成员初始化为 0 表示没有赋值?

    一个简单的解决方案是用 0 初始化你的结构(例如),然后将每个成员与它进行比较。示例:

    struct cube shape = {0};
    shape.width = 3;
    if (shape.width != 0)
        printf("width was set");
    

    或者更简单:

    struct cube shape = {2,0,3};
    if (shape.width != 0)
        printf("width was set");
    

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多