开发者

How do I name a structure using a variable?

开发者 https://www.devze.com 2023-03-16 21:18 出处:网络
This is got to be simple, but I can\'t figure it out.How do I name a structure using a variable, for example...

This is got to be simple, but I can't figure it out. How do I name a structure using a variable, for example...

 char *QueryName = "GetAirports";   
 Query QueryName = malloc(sizeof(Query) + RecordCount*sizeof(int));

where "Query" is the name of a structure. Thanks fo开发者_JAVA技巧r the help.


In C you have to either use struct keyword where you use struct types, or use a typedef, like this:

typedef struct query
{
  // ....
} query_t;

int main ()
{
  query_t *q = malloc (sizeof (query_t));
  return 0;
}


I'm not sure I see the need to use the variable. Why not just do:

Query GetAirports = malloc(sizeof(Query) + RecordCount*sizeof(int));
Query GetRunways = malloc(sizeof(Query) + RecordCount*sizeof(int));

Since C is a statically-typed compiled language, the names of objects such as GetAirports and GetRunways here are used at compile time, but do not exist at runtime. Therefore, it is not possible to use, at runtime, the contents of a string variable to refer to an object by name.


I assume that you're attempting to recreate what is allowed in more dynamic languages, such as this PHP example:

$QueryName = "GetAirports";
$$QueryName = array(/*...*/);

Where by altering the value of $QueryName variable you can refer to another object?

If so, the simple answer is: you can't do that in C.

What you can do, however, is use a single variable to point to multiple instances at different times.

Query *query_ptr = &myFirstQueryObject;
query_ptr = &mySecondQueryObject;
/* etc */

However from your example code it appears you're simply wanting to allocate a structure? If so:

typedef struct Query {
    /* fields here, e.g: */
    int id;
    int age;
} Query_t;

int main()
{
    Query_t *query = malloc(sizeof(Query_t));

    query->id = 1;
    query->age = 0;

    /* etc. */

    return 0;
}

Perhaps look up C structs and pointers.

EDIT so from further comments apparently you're wanting to create a map of char* name to Query object? There are several approaches for this, but the simplest is to create two arrays:

char *names[];
Query *queries[];

As long as both arrays have the same number of elements, and the *n*th element in names corresponds with the *n*th in queries, you can iterate through names until you find your matching string, then use the current index to dereference the appropriate object in queries, or vice versa


To answer your question in brief: You cannot. You cannot assign the names of identifiers at runtime. Identifiers are a compile-time concept that are not even visible in the compiled result (in general). C is not a reflective language and cannot at runtime invoke its own compiler, as it were.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号