在C中迭代相同类型的结构成员 [英] Iterating over same type struct members in C
问题描述
是否可以使用指针迭代所有成员都属于同一类型的 C 结构.以下是一些无法编译的示例代码:
Is it possible to iterate of a C struct, where all members are of same type, using a pointer. Here's some sample code that does not compile:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int mem1 ;
int mem2 ;
int mem3 ;
int mem4 ;
} foo ;
void my_func( foo* data )
{
int i ;
int* tmp = data ; // This line is the problem
for( i = 0; i < 4; ++i )
{
++tmp ;
printf( "%d
", *tmp ) ;
}
}
int main()
{
foo my_foo ;
//
my_foo.mem1 = 0 ;
my_foo.mem2 = 1 ;
my_foo.mem3 = 2 ;
my_foo.mem4 = 3 ;
//
my_func( &my_foo ) ;
return 0 ;
}
假设您的编译器/内核不会尝试为缓冲区溢出提供堆栈保护,则 foo 的成员应该在内存中一个接一个地对齐.
The members of foo should be aligned in memory to be one after another, assuming your compiler/kernel does not try to provide stack protection for buffer overflow.
所以我的问题是:
我将如何迭代 C 结构中具有相同类型的成员.
How would I iterate over members of a C struct that are of the same type.
推荐答案
最简单的方法是创建一个联合,一部分单独包含每个成员,一部分包含数组.我不确定依赖于平台的填充是否会干扰对齐.
The easiest way would be to create a union, one part which contains each member individually and one part which contains an array. I'm not sure if platform-dependent padding might interfere with the alignment.
这篇关于在C中迭代相同类型的结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!