c - 有没有更好的方法来迭代指针而不将其重新分配给不同的变量?
问题描述
struct hello1 {
int64_t world1;
int64_t world2;
int64_t world3;
int64_t world4;
int64_t world5;
}
void something (struct hello1 *first) {
int64_t *foo1 = &first->world1;
for (int64_t i = 0; i < 0x30; i++) {
printf("Address: 0xllx", foo1);
foo1++;
}
}
我目前正在将地址 , 分配&first->wordl1
给 *foo1。
有没有更好的方法来增加结构中的下一个指针而不创建int64_t *foo1
?
解决方案
尝试struct
通过指针算术从任何其他成员访问 的任何成员的行为是未定义的。
更详细地说,C 标准允许您读取指针值&world1
(并取消引用它)和指针值&world1 + 1
(但不延迟它)。但它不允许您读取指针值&world1 + 2
及以上。
考虑使用数组int64_t
代替。然后指针算术将是有效的,并且您不需要那些额外的演员表。
如果您坚持hello1
原样并希望能够通过索引访问成员,请考虑
inline int64_t* getHello1Element(struct hello1* h, size_t i)
{
switch (i){
case 0:
return &h->world1;
case 1:
return &h->world2;
case 2:
return &h->world3;
case 3:
return &h->world4;
case 4:
return &h->world5;
}
}
这将是 O(1) 与一个好的编译器。
推荐阅读
- vuejs2 - 有没有办法干掉这些 Vue 属性?
- php - 如何使用 CK Finder 3 自动将图像保存在不同的文件夹中
- react-testing-library - 来自 getByLabelText 的打字稿 HTMLInputElement
- entity-framework-core - EF Core - 以编程方式创建数据库
- java - Spring JPA - “java.lang.IllegalArgumentException:投影类型必须是接口!” (使用本机查询)
- python - 在python中用隐式欧拉求解PDE - 输出不正确
- c++ - 如果我们已经手动解锁了 unique_lock 是否会在销毁时解锁?
- ios - 连接airpods时音频未切换到扬声器
- c# - 将表值绑定到组合框时出错 - wpf
- postgresql-9.3 - 如何将mysql枚举转换为postgres