开发者

Can you make a c struct from an array of specific length?

I'm working on a C program that generates a doubly linked list of "records".

I've got my structs prototyped as follows:

struct custRec(char[20] name, char[50] address, char[20] city,
         char[2] stateAbbreviation, int zipCode, float balance);
struct linkedRec(custRec storedRec, custRec* nextRec, custRec* prevRec);

Specifically, for my custRec struct, is it valid to use char[20] name instead of char[] name?

By "valid", I mean -- I'm trying to limit the "name" field to exactly 19 characters (+ null terminator). Should I worry about length elsewhere and make t开发者_开发知识库he struct accept char arrays of any length?


This syntax is incorrect (I misread the question at first because they look like function declarations, not structure definitions):

struct custRec(char[20] name, char[50] address, char[20] city,
         char[2] stateAbbreviation, int zipCode, float balance);
struct linkedRec(custRec storedRec, custRec* nextRec, custRec* prevRec);

You probably meant:

typedef struct custRec
{
    char  name[20];
    char  address[50];
    char  city[20];
    char  stateAbbreviation[2];
    int   zipCode;
    float balance;
} custRec;  // Necessary because question is about C, not C++

typedef struct linkedRec
{
    custRec  storedRec;
    custRec *nextRec;
    custRec *prevRec;
} linkedRec;

I note that in the US, state abbreviations are 2 characters, so you probably need to use char state[3] to allow for the terminating null.

This is now syntactically valid. When you copy data into the fields of the custRec, you will need to be careful to ensure that your copying does not overflow the bounds. The compiler does not enforce the lengths.

You will need to check, therefore, inside the function that the strings passed to you do not exceed the limits you expect.

If you prefer not to impose limits on the lengths, all the string structure members can be made into char * and you can dynamically allocate the memory for arbitrary length strings. But that is probably not a good idea for US state abbreviations; there you do want to enforce the '2 characters plus '\0'' limit.


Yes, it is common to declare structures with fixed length strings as you describe. You will need to be very careful to ensure that all operations ensure they don't exceed the length, and also terminate the fields correctly. Otherwise you will get all sorts of weird bugs.

And yes, you would need to specify char[20] rather than char[], as you need to reserve space for the data.

Note however that this does place an arbitrary upper limit on these fields, and makes it far more difficult to extend later on. Consider having regular char* fields, and allocating strings on the heap so you can handle any length strings. This requires some care with memory management also (especially cleaning up!).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜