Pointer of structure initialization to NULL

China☆狼群 提交于 2019-12-25 02:49:16

问题


I'm having a problem with a structure within a structure:

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

my compiler says that about the line with the SDL_Surface structure:

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

But I don't really understand because I got in front of me my teacher's lesson about pointer of structure saying that: Coordinate *point = NULL;

Coordinate being a structure with two int inside: int x,y;

Can somebody explain me that weird thing ?

Thanks


回答1:


The C language does not allow for the initialization of instance fields inline like this. The standard practice is to write a factory style method which does the initialization for you

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



回答2:


thanks, that's been really helpful and you took a weight off my mind. Since I already use a function to initialize my coordinates, I will initialize my surfaces at the same time.

To be real really clear: my structure will now looks like this, right ?:

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;


来源:https://stackoverflow.com/questions/22258776/pointer-of-structure-initialization-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!