开发者

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.

A fault has 3 piece of information: 1. Number of开发者_Go百科 fault. 2. Fault name. 3. Date time of fault.

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.

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 (e.g., 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜