具有枚举成员的结构数组在为数组提供NULL终止时会导致错误,但在不这样做时不会导致错误



我试着搜索过这个,但我没有找到导致这种奇怪行为的原因,一定有我丢失的东西,但我不知道是什么:

问题是以下我有以下结构:

struct s_log_message{
lll level;
const unsigned int i;
const char *msg;
}typedef log_message;

以及所述结构的以下阵列:

const log_message logging_messages[]{
{
error,
0,
ACR "ERROR" ACS ":" "No arguments given, use -h or --help for information on how to use the program"
},
NULL
};

ACR和ACS被定义为改变终端颜色。

lll级别是一个枚举:

enum log_level_list{none=0,info=1,warn=2,error=3};
typedef enum log_level_list     lll;

所有这些代码都在3个不同的文件中:

log.h:

#ifndef LOG
#define LOG 220
enum log_level_list{none=0,info=1,warn=2,error=3};
typedef enum log_level_list     lll;
class log{
public:
static void                         set_log_level(lll val);
static unsigned char        get_log_level(void);
static void                         l(unsigned int warn_i);
private:
log(){}
static unsigned char        log_level;
};
#endif

lmg.h:

#ifndef     LOG_MESSAGES
#define     LOG_MESSAGES    100
#include "../lib/log.h" //included for definition of enum type lll
struct s_log_message{
lll level;
const unsigned int i;
const char *msg;
}typedef log_message;
extern const log_message logging_messages[];
#endif

和lmg.cpp:

#include "../lib/col.h"         //terminal color defines
#include "../lib/lmg.h"         //header for this file
#include <cstddef>                  //included for definition of NULL
const log_message logging_messages[]{
{
error,
0,
ACR "ERROR" ACS ":" "No arguments given, use -h or --help for information on how to use the program"
},
NULL
};

概括一下,问题是用NULL终止loggin_messages[]数组会导致编译器抛出以下错误:

g++ -Wall -o DFHM ./src/main.cpp ./lib/lib.cpp ./lib/EasyBMP.cpp ./lib/dat.cpp ./lib/log.cpp ./lib/lmg.cpp
./lib/lmg.cpp:12:1: error: invalid conversion from ‘long int’ to ‘lll’ {aka ‘log_level_list’} [-fpermissive]
12 | };
| ^
| |
| long int
make: *** [makefile:14: main] Error 1

我知道在这么多文件中传播这么少的代码会适得其反,我只是想习惯这样做,这样,如果我进入更大的项目,我就会习惯,当然也会练习。

NULL是一个空指针常量。它旨在将指针设置为null,而不是指向任何东西。

logging_messages不包含指针。它是一个log_message对象的数组。将log_message初始化为NULL没有任何意义。

如果你想添加一个";"空";对象作为数组的终止符,而不是单独存储数组的大小,您可以这样做,但您的类型的";"空";州由你决定。例如CCD_ 6可以是您定义的";"空";状态该特定状态也可以写成简单的{},因为在聚合初始化中未给定的成员将被值初始化。

您不需要用NULL终止每种类型的数组。事实上,严格来说,即使是char数组也不需要以NULL终止。只要编写代码,就可以愉快地使用非NULL终止的数组,这样就不会超出数组的末尾。

当然,对于char数组,有一个既定的约定,即许多函数将NULL值的char解释为有用数据的结束。然而,这种想法并没有适用于任何其他类型的数组。

或者换一种说法,NULL不是struct(或class等(的有效值。虽然这是一个指向一个的指针,但这是一种完全不同的类型。当您有一个事物的实际实例(例如struct(时,它不能为NULL。

最新更新