【发布时间】:2015-02-22 01:52:26
【问题描述】:
我已经进行了一些研究,但在这里或谷歌上找不到我想要的东西。有没有办法通过地址(而不是使用 customer[i].bottles)访问 Customer 中的元素。我无法修改结构,因此无法将属性放入数组中。
typedef struct Customer {
int id;
int bottles;
int diapers;
int rattles;
} Customer;
Customer customers[100];
void setValue(int custInd, int propertyInd) {
//propertyInd would be 1 for id, 2 for bottles
//Attempting to set customers[0].bottles
*(&customers[custInd]+propertyInd) = 5;
}
我以为我能做到这一点,但我遇到了各种错误。知道“瓶子”值将是客户地址中内存中的第二个空间,我不应该能够直接设置该位置。
我知道这可能是不正确的代码,但我想了解它是如何工作以及为什么工作/不工作。我还保证我有理由尝试以传统方式进行此操作哈哈
【问题讨论】:
-
这个
*(&customers[custInd]+propertyInd) = 5和customers[custInd+propertyInd] = 5基本一样,你为什么不直接做switch (propertyInd) { case 0: customers[custInd].id = 5; default: break'}呢? -
C 还是 C++?选择一个。