简体   繁体   中英

How can I tell the difference between an initialized struct and an uninitialized struct?

I am sending student records over a socket. The database sends the client the number of students in the list and then sends the records one at a time. The problem I am coming across is that when there are no students the list starts with an uninitialized record. I thought about adding a new field to the records that stated if they were a new record or had been filled but that would mean changing A LOT of the code.

Is there an easy way to check a record to see if it has been filled. Below is the structure for the student records.

typedef struct student{
    char lname[10], initial, fname[10];
    unsigned long SID;
    float GPA;
} SREC;

typedef struct node{
    SREC student;
    int deleted;
    struct node *left;
    struct node *right;
} NODE;

This is what initialization is done for the starting empty node.

NODE *lname = calloc( 1, sizeof(NODE) );
lname->left = NULL;
lname->right = NULL;
lname->deleted = 0;
  1. If the null pointer on your system has an all-zero bit pattern (and it probably does), you don't need any of that code after calloc .

  2. You can track if a record has been initialized by looking at any field that doesn't have a legitimate all-zero value. Maybe the lname or SID fields?

An uninitialized record could have anything in it. In fact, at a very low probability it could coincidentally have something interesting, or even the written exposition at the beginning of Star Wars in it. You can't rely on the contents of uninitialized memory.

As such you'll need to introduce something to track whether or not the data in the structure is filled in, and deliberately set it to the appropriate value (which is, in a way, initializing the structure.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM