user968000 user968000 - 2 months ago 11
C Question

Adding offset to all elements in a structure

Is there a way to add an offset to all elements in a structure in one go.

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

Answer

Ok let me start of with a disclaimer: this is definitely bad style and I don't know why you would want to do it.

Key points:

  1. This only works if all the elements in the struct are of the same type
  2. This will work for arbitrarily many attributes of the same type in the struct
  3. This might not work at all due to padding between members. I doubt it is likely, but it is not guaranteed by the C standard.
  4. Why not just make a method to do it?
  5. Did I mention this is bad style?

Have fun:

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

Output:

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

Wash your hands thoroughly after you're done.