简体   繁体   English

初始化大量结构

[英]Initialize large array of structs

I need to store a lot of information about certain resolutions at some way, I would like to make a struct for this. 我需要以某种方式存储有关某些分辨率的大量信息,我想为此做一个结构。

struct resolution{
    const char* name;
    const int width;
    const int height;
};

The problem is I need to store a lot of resolutions in some array of structs, but can't get this work properly (need to store 126 things to it 'manual', so no loops or that kind of stuff. 问题是我需要在一些结构数组中存储很多分辨率,但是无法正常工作(需要“手动”存储126项内容,因此没有循环或此类内容。

Thanks! 谢谢!

Have you tried an initializer? 您是否尝试过初始化程序?

struct resolution {
  const char * name ;
  const int width ;
  const int height ;
}
  mylist[] = 
  {
    { "cga", 320, 240 },
    { "vga", 640, 480 },
    { "xga", 1024, 768 },
  } ;

As a bonus, you can store a sentinel at the end so any loop that reads these can stop on the value instead of keeping track of how long the list is: Using something like: 另外,您可以在末尾存储一个前哨,从而使读取这些内容的任何循环都可以在值上停止,而不必跟踪列表的长度:使用类似以下内容的方法:

{ NULL, 0, 0 }

So you can check if the name is NULL or the size, like this: 因此,您可以检查name是否为NULL或大小,如下所示:

const struct resolution *  find_bysize( int w, int h )
{
  struct resolution * searchptr ;

  for (searchptr= mylist ; ( searchptr-> name ) ; searchptr ++ )
    { if (( searchptr-> width == w ) && (searchptr-> height == h )) { return searchptr ; } }
  return NULL ;  // not found
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM