如何使用变量命名结构?
这一定很简单,但我无法弄清楚。例如,如何使用变量命名结构,
char *QueryName = "GetAirports";
Query QueryName = malloc(sizeof(Query) + RecordCount*sizeof(int));
其中“Query”是结构的名称。感谢您的帮助。
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 for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C 中,您必须在使用结构类型的地方使用 struct 关键字,或者使用 typedef,如下所示:
In C you have to either use
struct
keyword where you use struct types, or use a typedef, like this:我不确定是否需要使用该变量。为什么不直接这样做:
由于 C 是静态类型编译语言,因此这里的 GetAirports 和 GetRunways 等对象名称是在编译时使用的,但是 运行时不存在。因此,在运行时不可能使用字符串变量的内容来按名称引用对象。
I'm not sure I see the need to use the variable. Why not just do:
Since C is a statically-typed compiled language, the names of objects such as
GetAirports
andGetRunways
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.我假设您正在尝试重新创建更动态的语言中允许的内容,例如这个 PHP 示例:
Where by altering the value of
$QueryName
变量,您可以引用另一个对象?如果是这样,简单的答案是:您不能在 C 中这样做。
但是,您可以做的是使用单个变量指向不同时间的多个实例。
但是从您的示例代码看来您只是想分配一个结构?如果是这样:
也许查找 C 结构和指针。
编辑,因此从进一步的评论来看,显然您想要创建
char*
name 到Query
对象的映射?有多种方法可以实现此目的,但最简单的是创建两个数组:只要两个数组具有相同数量的元素,并且
names
中的第 *n* 个元素与 *n* 相对应在queries
中,您可以迭代names
直到找到匹配的字符串,然后使用当前索引取消引用queries
中相应的对象,或反之亦然I assume that you're attempting to recreate what is allowed in more dynamic languages, such as this PHP example:
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.
However from your example code it appears you're simply wanting to allocate a structure? If so:
Perhaps look up C structs and pointers.
EDIT so from further comments apparently you're wanting to create a map of
char*
name toQuery
object? There are several approaches for this, but the simplest is to create two arrays:As long as both arrays have the same number of elements, and the *n*th element in
names
corresponds with the *n*th inqueries
, you can iterate throughnames
until you find your matching string, then use the current index to dereference the appropriate object inqueries
, or vice versa简单回答你的问题:你不能。您无法在运行时分配标识符的名称。标识符是一个编译时概念,在编译结果中甚至不可见(通常)。 C 不是反射语言,不能在运行时调用它自己的编译器。
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.