【问题标题】:C Passing a struct, that contains a struct arrayC 传递一个包含结构数组的结构
【发布时间】:2014-12-05 21:17:42
【问题描述】:

我正在尝试一个包含在另一个结构中的结构数组 EG (Struct1.StructArray[])

代码如下所示:

struct bullet{
    int x;
    int y;
    int exist;
    int type;
};

struct tank{
    int x;
    int alive;
    int shotsfired;
    struct bullet shots[50];
};

我试图将镜头 [] 结构体作为指向以下函数的指针传递。

int get_alien_collision(struct bullet *bulletStruct)

我用来传递结构的代码行如下。

a = get_alien_collision(&player.shots[i])

但是,我无法访问函数内部镜头 [i] 中的任何数据(我通过尝试在前 20 个屏幕上打印“bulletStruct->x”的值来确认这一点,它们都是 0即使它在 main()) 中的结构打印得很好

Main.ccalculations.c 的完整代码(在 pastebin 上)它非常混乱,可能充满了许多不良做法,因为这是我第一次编写代码(我相信是 C)

【问题讨论】:

  • ...你“相信什么是 C”?你不确定你在用什么语言编程?另外,请尝试在您的问题中添加MCVE。 Pastebin 适合完整的代码清单,但您应该在实际问题中包含代码的相关部分。
  • 由于我不确定 c 的标准文本输出或调试输出,我很难准确地确定重写代码需要什么。因为我正在为没有标准调试输出的 3ds 编码。我正在尝试编写一个更简化的问题版本,尽管它仍然做同样的事情。
  • 我在问题中的代码 sn-p 中没有看到明显的问题,而且,正如你所说,完整的程序有点复杂。请尝试进一步煮沸。您很可能会在此过程中遇到解决方案。
  • @JasonBrown printf(format, ...)fprintf(stderr, format, ...)
  • 当我在测试环境中运行它时,我似乎无法得到相同的问题结果。

标签: c arrays struct


【解决方案1】:

如果你想更明确,你可以使用括号,或者你可以通过定义中间体来确保你传递了正确的东西:

struct bullet currentBullet=player.shots[i];
struct bullet *bp=&currentBullet;
get_alien_collision(bp);

【讨论】:

    【解决方案2】:

    您传递的结构看起来不错,但在您的函数中您分配给 bulletStruct 而不是测试等价性。

    if ((bulletStruct->x = alienPPositionx + x)&&(bulletStruct->y = alienPPositiony + y))
    

    应该读一下

    if ((bulletStruct->x == alienPPositionx + x)&&(bulletStruct->y == alienPPositiony + y))
    

    解决这个问题的一种方法是使用 const 参数声明函数

    void function ( struct bullet const* bulletStruct)...
    

    【讨论】:

      猜你喜欢
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多