printf 结构像一个数组 C

printf struct like an array C

我有一个结构体,希望像数组一样打印所有成员变量。

结构就像

#pragma pack(push)     /* push current alignment to stack */ 
#pragma pack(1)     /* set alignment to 1 boundary */ 
struct testStruct { 
    int a = 6; 
    int b[5] = {1,2,3,4,5}; 
} testStruct1 ;
#pragma pack(pop)     /* restore original alignment from stack */

我正在尝试

for(int i = 0; i < 6; i++)
{
    printf("%d, ", testStruct1 + i);
}

这无法编译。我不愿意为其中的所有成员 memcpy 声明一个新数组。

我想看

6, 1, 2, 3, 4, 5, 

有什么办法吗??? 谢谢

如果你想使用 pragamas 那很好,但它们对你的问题没有影响。

我相信你想要的语法是:

struct testStruct { 
    int a; 
    int b[5]; 
} testStruct1 = {6,1,2,3,4,5};

你可以这样打印:

printf("%d, %d, %d, %d, %d, %d\n",
    testStruct1.a,
    testStruct1.b[0];
    testStruct1.b[1],
    testStruct1.b[2],
    testStruct1.b[3],
    testStruct1.b[4]);

请删除所有多余的空行。

听起来您希望通过不同的类型和名称访问相同的变量。 C 允许您通过“联合类型双关”来做到这一点,就像这样:

#include <stdio.h>

typedef union
{
  struct  // standard C anonymous struct
  {
    int a; 
    int b[5];
  };
  int array [6];
} testArray;

int main (void)
{
  testArray test = { .a = 6, .b={1,2,3,4,5} };
  
  for(int i=0; i<6; i++)
  {
    printf("%d ", test.array[i]);
  }
  
  return 0;
}

输出:

6 1 2 3 4 5

在这种情况下不需要打包,因为它都是对齐的 int 个变量。