Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing multiple strings in nested structure

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

NOTE: I cannot change the array

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

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading