Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        3年前关闭。
                                                                                            
                
        
有没有一种方法可以一次性向结构中的所有元素添加偏移量。

#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 );
}

最佳答案

好吧,让我从免责声明开始:这绝对是不好的风格,我不知道您为什么要这么做。

关键点:


仅当结构中的所有元素均为相同类型时,此方法才有效
这将适用于结构中任意多个相同类型的属性
由于成员之间的填充,这可能根本不起作用。我怀疑这可能发生,但是C标准不能保证。
为什么不只是制定一种方法呢?
我是否提到过这种不好的风格?


玩得开心:

    #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/

10-12 16:08