命名的变量在C另一个变量 [英] Naming a variable with another variable in C

查看:117
本文介绍了命名的变量在C另一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个结构与2个变量,如

I want to create a struct with 2 variables, such as

struct myStruct {
char charVar;
int intVar;
};

和我将命名为结构:

struct myStruct name1;
struct myStruct name2;

等。

问题是,我不知道有多少变量将被输入,所以必须有无限的nameX结构。

The problem is, I don't know how many variables will be entered, so there must be infinite nameX structures.

所以,我怎么能说出这些结构变量?

So, how can I name these structures with variables?

感谢。

推荐答案

您应该使用数组和指针。

You should use an array and a pointer.

struct myStruct *p = NULL;
p = malloc(N * sizeof *p);  // where N is the number of entries.
int index = 1; /* or any other number - from 0 to N-1*/
p[index].member = x;

然后,您可以通过添加元素为的realloc 如果您需要添加额外的条目。

Then you can add elements to it by using realloc if you need to add additional entries.

这篇关于命名的变量在C另一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆