[英]Using structs or multidimensional arrays in C
I want to create a fault log. 我要创建一个故障日志。 The fault log should be able to store the last 10 faults.
故障日志应该能够存储最近的10个故障。
A fault has 3 piece of information: 1. Number of fault. 故障具有3条信息:1.故障数量。 2. Fault name.
2.故障名称。 3. Date time of fault.
3.故障日期时间。
How can i do this using structs? 如何使用结构来做到这一点?
Or should i do it using arrays and if so how? 还是我应该使用数组,如果可以的话?
The fault log is for storage in memory only. 故障日志仅用于存储在内存中。
I assume you want to store it in the memory, then you can use a combination of struct and array. 我假设您要将其存储在内存中,然后可以使用struct和array的组合。
Something like will following will do: 将会执行以下操作:
typedef struct {
int number;
char* name; // You can use an array instead char name[MAX_FAULT_NAME_LENGTH]
int timestamp;
} fault_entry;
fault_entry fault_log[10];
Of course this is hand-waving. 当然,这是费力的。 If you want to store it to a file, you need to serialize.
如果要将其存储到文件中,则需要序列化。 You need to think about what data-type to use for date/time and name.
您需要考虑使用哪种数据类型作为日期/时间和名称。 But it should help you get started.
但这应该可以帮助您入门。
A log usually implies some kind of more permanent storage, which might mean that it should be written to a file. 日志通常意味着某种更永久的存储,这可能意味着应该将其写入文件。 If so, then a structure is not necessarily required.
如果是这样,则不一定需要结构。 It could be implemented as a function that accepts the required information and generates the other information (eg, time/date).
它可以实现为接受所需信息并生成其他信息(例如时间/日期)的功能。
But if it is indeed more of a temporary type of storage, then it could be stored in a simple circular array. 但是,如果确实确实是临时存储类型,则可以将其存储在简单的循环数组中。 Keep an index of the current position in the array and write to that position.
保留数组中当前位置的索引并写入该位置。
typedef struct {
int faultNumber;
char faultName[50]; // length should probably be a #define
char faultDate[20]; // date in C could be stored in some kind of char array.
// or it could be something representing results of something
// like a time_t result.
} LOG_ENTRY;
LOG_ENTRY LOGS[10];
int iCurPos = 0;
Then add an entry at the current position and increment iCurPos and loop it back to 0 when it hits the end. 然后在当前位置添加一个条目,并递增iCurPos,并在结束时将其循环回到0。
You should use an array of the struct type such as 您应该使用结构类型的数组,例如
#define NAME_MAXLEN 20
struct fault {
int number;
time_t time;
char name[NAME_MAXLEN];
};
struct fault faults[10];
]; ]。
Something along the lines of: 类似于以下内容:
typedef struct fault
{
int number;
char *name;
char *date;
} fault;
fault faults[10];
faults[0].number = 1;
faults[0].name = "Fault Number 1";
faults[0].date = "Today's Date";
/*etc*/
printf("%d\n", faults[0].number);
printf("%s\n", faults[0].name);
printf("%s\n", faults[0].date);
You will need to decide what time type to use of course. 您将需要确定当然要使用哪种时间类型。 Here, i've used a string.
在这里,我用了一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.