【发布时间】:2015-07-31 01:41:18
【问题描述】:
如何在 C 的循环中增加变量名?例如,我有一个变量 K1,我想在每次循环到 K2、K3、K4 等时将名称加一。我不能使用数组,因为我有大约 1000 个变量要循环。
更新:我应该澄清一下我正在对微控制器进行编程,并且板上的空间非常有限。我希望循环的变量名称是结构,每个 8 字节长。因此,要创建一个包含我之前创建的结构的数组,我必须写出一个包含 1000 个数组名称的数组吗?当然有一种方法可以增加名称吗? 稍后我会发布我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
typedef struct reg0 {
int address;
union {
struct {
unsigned int bitfield1 : 1;
unsigned int bitfield2 : 4;
unsigned int bitfield3 : 2;
unsigned int bitfield4 : 1;
};
uint8 DATA;
};
} Reg0;
//Beneath this I have 1000 similar Register structures, each unique
int main()
{
//Beneath this I have 1000 similar initializations, each unique
Reg0 R0 = {.address = 0x0, {{.bitfield1=0x1,.bitfield1=0x6,.bitfield3=0x2,.bitfield4=0x1}}};
for(i=0;i<=1000;i++){
//Here I'd like to print each address field of each structure to the screen
printf("Address of Reg%d is: %?", i, Ri);
}
return 0;
}
【问题讨论】:
-
我不明白为什么你不能使用数组...... 1000 项并不多。您可以轻松处理数百万美元。
-
我不能使用数组,因为我有大约 1000 个变量要循环。 我会说你 不能 使用变量作为 您将有 1000 个变量要循环遍历 .... 在 C 中,您不能在运行时动态创建变量并更改它们的名称。这就是数组的用途
-
如果你有 1000 个变量叫做
K1...K999,在学习数组之前不要再修改你的代码。