c - 向结构中的所有元素添加偏移量

标签 c

有没有一种方法可以一次性为结构中的所有元素添加偏移量。

#include <stdio.h>

struct date {           /* global definition of type date */
    int month;
    int day;
    int year;
};

main()
{

    struct date  today;

    today.month = 10;
    today.day = 14;
    today.year = 1995;

    //I want to add 2 to month/day/year.
    today.month += 2;
    today.day += 2;
    today.year += 2;

    printf("Todays date is %d/%d/%d.\n", \
        today.month, today.day, today.year );
}

最佳答案

好吧,让我先声明一下:这绝对是糟糕的风格,我不知道你为什么要这样做。

要点:

  1. 只有当结构中的所有元素都属于同一类型时,这才有效
  2. 这适用于结构中相同类型的任意多个属性
  3. 由于成员之间存在填充,这可能根本不起作用。我怀疑这可能,但 C 标准并不能保证这一点。
  4. 为什么不直接制定一个方法来做到这一点?
  5. 我有没有提到过这种风格很糟糕?

玩得开心:

    #include <stdio.h>
    #include <assert.h>

    struct date {
        int month;
        int day;
        int year;
    };


    int main() {
        struct date d;
        d.month = 10;
        d.day = 14;
        d.year = 1995;
        printf("Before\n\tm: %d, d: %d, y: %d\n", d.month, d.day, d.year);
        size_t numAttributes = 3;
        assert(sizeof(struct date) == numAttributes*sizeof(int));
        for(int i = 0; i < numAttributes; ++i) {
            int *curr = (int *)((char *)&d + i*sizeof(int));   // memory address of current attribute.
            *curr += 2;                                                 // how much you want to change the element
        }
        printf("After\n\m: %d, d: %d, y: %d\n", d.month, d.day, d.year);
        return 0;

输出:

Before
    Month: 10, Day: 14, Year: 1995
After
    Month: 12, Day: 16, Year: 1997

完成后彻底洗手。

关于c - 向结构中的所有元素添加偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39420458/

相关文章:

c - 如何使用 pthread_cond_signal 和 pthread_cond_wait 使 pthreads 工作正常?

c - 普通 `int` 位域的符号

c - 错误 LNK1120 : 1 unresolved external - VS13 C

c - 预测由 C (glibc) rand() 生成的下一个数字

c - 递归如何在二叉搜索树中工作?

c - 头文件中的静态常量变量声明

C - 编译器优化将如何影响没有主体的 for 循环?

c - 从用户获取字符串并使用 strlen() 查找其长度时出现段错误(核心转储)

c - 声明一个返回数组的函数指针

c - 结构作为参数传递给函数但无法正常工作