C:指向函数中的结构数组的指针

问题描述 投票:0回答:1

我想创建一个将根据条件启用或禁用某些功能的功能。我创建了一个包含4个成员的结构(枚举类型,uint8 catNumber,char名称,bool标志)。

typedef struct MYSTRUCT
{
 enum modes;
 uint8 catNumber;
 char name;
 bool flag;
 }mystruct;

枚举包含:

typedef emum MODES {mode1, mode2, mode3}modes;

因此,在创建结构模板之后,我声明了结构类型的数组变量。即结构mystruct变量[3]。并且我已经初始化了mystruct的每个成员。

mystruct  Variable[3] = 
{
[0] ={.modes=mode1,
.catNumber=1,.name = “catA”,
.flag=false},

[1] = {.modes =mode2,
.catNumber=2,.name = “catB”,
.flag=false},

[2] = {.modes =mode3,
.catNumber=3,.name = “catC”,
.flag=false},
};

因此,用户必须输入类别编号和true / false标志才能启用或禁用部分功能,即与struct不同的类别,并在每个相应的模式下打印模式名称以检查其是否启用。因此,任务是用户可以启用一个或多个类别。例如。用户输入:1 2是。这将同时启用类别1和2。

有人可以指导我如何执行此任务吗?并且有可能不将整个struct数据类型作为func参数传递。我只想声明指针作为指向main()中的结构数组元素的参数。

c function pointers struct enums
1个回答
0
投票

基本上有两种方法将可变长度数组从一个函数发送到另一个函数。一个变体是提供数组(基本上是指向其第一个元素的指针)和元素的数量。另一个选择是定义一个特殊的终止元素。就像C中的字符串一样-它们以代码0的特殊字符终止。这是我的代码,基于您的代码和一些更正。

#include <stdio.h>
#include <stdint.h>

typedef enum MODES {mode1, mode2, mode3, modeTerminus} modes;

typedef struct MYSTRUCT
{
    enum MODES modes;
    int8_t catNumber;
    const char * name; //As we intend to store a string here, a simple 'char name' is insufficient
    bool flag;
} mystruct;

mystruct Variable[] =
{
    [0] ={
        .modes=mode1,
        .catNumber=1,.name = "catA",
        .flag=false
    },

    [1] = {
        .modes =mode2,
        .catNumber=2,.name = "catB",
        .flag=false
    },

    [2] = {
        .modes =mode3,
        .catNumber=3,.name = "catC",
        .flag=false
    },
    [3] = {
        .modes =modeTerminus
    },
};
void theDataProcessor1(mystruct* theList)
{
   for (const mystruct* theItem=theList; theItem->modes!=modeTerminus; theItem++)
      printf("theDataProcessor1: modes=%d catNumber=%d name=%s flag=%d\n",
              theItem->modes,
              theItem->catNumber,
              theItem->name,
              theItem->flag
            );
}
void theDataProcessor2(mystruct* theList, int Count)
{
    for (int i=0; i<Count; i++)
      printf("theDataProcessor2: modes=%d catNumber=%d name=%s flag=%d\n",
              theList[i].modes,
              theList[i].catNumber,
              theList[i].name,
              theList[i].flag
            );
}
int main()
{
    theDataProcessor1(Variable);
    theDataProcessor2(Variable, 3);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.