我对使用菜单管理结构体数组有一些疑问。 我有一个简单的菜单,可根据用户选择添加或删除项目,然后打印它们。
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX_CHAR_TEST 20
#define MAX_ARRAY_TEST 50
typedef struct
{
int idTest;
char nameTest[MAX_CHAR_TEST];
int numTest;
// etc..
} sTest;
void addElement(sTest *arrayTest,sTest *tempTest);
void delElement(sTest *arrayTest,const int tempID);
void printElements(sTest *arrayTest);
int main(void)
{
sTest arrayTest[MAX_ARRAY_TEST];
bool bEsc = false;
int select;
do
{
scanf("%d",&select);
switch (select)
{
case 1:
{
sTest tempTest;
// Simulate scanf
strcpy(tempTest.nameTest,"blabla1");
tempTest.numTest = 80; // Random number. It isn't important
//
addElement(arrayTest,&tempTest);
break;
}
case 2:
{
int tempID;
// Simulate scanf
tempID = 0;
//
delElement(arrayTest,tempID);
break;
}
case 3:
{
printElements(arrayTest);
break;
}
case 4:
{
bEsc = true;
break;
}
}
} while (bEsc == false);
return 0;
}
void addElement(sTest *arrayTest,sTest *tempTest)
{
SOME_INDEX = ??
arrayTest[SOME_INDEX].idTest = SOME_INDEX;
strcpy(arrayTest[SOME_INDEX].nameTest,tempTest->nameTest);
arrayTest[SOME_INDEX].numTest = tempTest->numTest;
}
void delElement(sTest *arrayTest,const int tempID)
{
int i;
for (i = 0; i < MAX_ARRAY_TEST; i++)
{
if (arrayTest[i].idTest == tempID)
break;
}
for (; i < MAX_ARRAY_TEST - 1; i++)
{
arrayTest[i] = arrayTest[i + 1];
}
}
void printElements(sTest *arrayTest)
{
int i;
for (i = 0; i < MAX_ARRAY_TEST; i++)
printf("%d - %s - %d",arrayTest[i].idTest,arrayTest[i].nameTest,arrayTest[i].numTest);
}
因此,每次将元素添加到数组时,索引都必须递增(因此也已存储)。
我的疑问是解决数组索引问题的最佳方法是什么?
我想到了两种不同的解决方案。
第一个:索引在main()函数中存储为变量,并在其中增加。
例如:
bool bEsc = false;
int select;
int index = 0;
addElement(&arrayTest[index],&tempTest,index);
index++;
void addElement(sTest *arrayTest,sTest *tempTest,const int index)
arrayTest->idTest = index;
strcpy(arrayTest->nameTest,tempTest->nameTest);
// etc
And also pass the "index" variable to the "printElements" function for the cycle condition.
第二个:索引存储为全局变量(更好是int还是int static?)
例如:
// etc..
} sTest;
int index = 0;
// or static int index??
And the rest of the code as above. So:
addElement(&arrayTest[index],index);
index++;
void addElement(sTest *arrayTest,const int index)
arrayTest->idTest = index;
strcpy(arrayTest->nameTest,tempTest->nameTest);
// etc
我还考虑过通过检查每个循环中的数组来查找第一个空索引,但是我认为这是不可能的(因为执行“ variable!= 0”是行不通的。)
还有其他方法吗?最好的方法是什么?