【问题标题】:Pointer of structure initialization to NULL结构初始化指针指向 NULL
【发布时间】:2014-03-07 19:14:43
【问题描述】:

我对结构中的结构有疑问:

typedef struct BrickStruct
{
    int type;
    SDL_Rect Brick_Coordinates;  
    SDL_Surface *Brick_Surface = NULL;  
}BrickStruct; 

我的编译器对 SDL_Surface 结构的行这么说:

error: expected ':', ',', ';', '}' or '__attribute__' before '=' token

但我真的不明白,因为我的老师关于结构指针的课程在我面前说: Coordinate *point = NULL;

坐标是一个内部有两个int的结构:int x,y;

谁能解释一下这个奇怪的事情?

谢谢

【问题讨论】:

  • 您不能在struct 的声明中初始化struct 的成员。

标签: c pointers structure


【解决方案1】:

C 语言不允许像这样内联初始化实例字段。标准做法是编写一个工厂风格的方法来为您进行初始化

BrickStruct create_brick_struct()
{
  BrickStruct s;
  s.Brick_Surface = NULL;
  s.type = <default type value>;
  s.Brick_Coordinates = <default coordinatos value>;
  return s;
}

【讨论】:

    【解决方案2】:

    谢谢,这真的很有帮助,你减轻了我的负担。由于我已经使用函数来初始化我的坐标,我将同时初始化我的表面。

    真的很清楚:我的结构现在看起来像这样,对吗?:

    typedef struct BrickStruct
    {
        int type;
        SDL_Rect Brick_Coordinates;  
        SDL_Surface *Brick_Surface;   // I'm just wondering if I need to make it a pointer here 
    }BrickStruct;
    

    【讨论】:

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