有没有一种方法可以一次性为结构中的所有元素添加偏移量。
#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/