Home > other >  Storing multiple strings in nested structure
Storing multiple strings in nested structure

Time:11-27

I have 2 structures named Phone and Patient, respectively:

struct Phone{
    char description[4];
    char number[10];
};

struct Patient{
    int id;
    char name[15];
    struct Phone phone;
};

Now, on creating a patient's array like:

struct Patient patient = [
    {1024, "Shaggy Yanson", {"CELL","3048005191"} },
]

Upon printing the phone description value, I get the output as CELL3048005191.

NOTE: I cannot change the array

I want to know what is causing the problem. Is it the structure definition?

CodePudding user response:

Yes it is. The problem is that C-style strings require one extra character to store a nul terminator. This is the character '\0' which is placed at the end of every C-style string. So, to store a string like "CELL" requires an array of size 5, not 4.

Of course, you can still store the 4 characters 'C', 'E', 'L' 'L' in an array of size 4. It's just that, then it's no longer a C-style string, because it no longer has a nul terminator. If this is what you want to do, then you will have to take special measures when you process the data (like, when you print it, for example).

  • Related