【问题标题】:printf struct like an array Cprintf 结构就像一个数组 C
【发布时间】:2020-12-23 14:49:51
【问题描述】:

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

结构是这样的

#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, 

有什么办法吗??? 谢谢

【问题讨论】:

  • printf( "%d, ", teststruct1.b[i] );
  • 写你自己的printX() 或者写一个在数组上运行的循环。 printf() 不知道如何打印数组。
  • 这不是初始化结构变量的正确方法
  • testStruct1 + i 是不正确的,因为 a) testStruct1 甚至不是指向结构的指针,b) 指向结构的指针也不会那样工作。

标签: arrays c struct printf


【解决方案1】:

听起来您希望通过不同的类型和名称访问相同的变量。 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 变量。

【讨论】:

  • 您好,代码 testArray test = { .a = 6, .b={1,2,3,4,5} };只适用于c,我怎么能在c++中做到这一点
  • @Olly 像初始化任何结构或数组一样初始化它吗?在 C++ 中,您也可以从构造函数初始化程序列表中执行此操作。 然而你不能在 C++ 中做类型双关语,这是未定义的行为。据说是因为 C++ 讨厌对硬件相关的编程有用...
【解决方案2】:

如果你想使用 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]);

请删除所有多余的空行。

【讨论】:

  • 或者 OP 可能想要使用循环,如果这段代码只是一个示例并且他实际上想在一个非常大的数组上使用它。
  • @APJo,当然这只是一个例子。循环很容易实现。也许他可以努力思考并自己做?
  • 当然,我只是发布了这个,所以他会想到它。或者,只要他知道自己在做什么,他就可以使用结构指针
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
  • 2013-10-29
  • 1970-01-01
  • 2011-11-06
相关资源
最近更新 更多