I am doing a book exercise (not homework, since i’m self-learning) in which I’m supposed to write a telephone book using an array of type struct.
So I defined:
typedef struct contact {
char cFirstName[10];
char cLastName[10];
char iTelphone[12];
} address ; // end type
Next, I defined:
address myContacts[5] = {
{
{ '\0' } // inner most braces,
// tell gcc to put 0 in all
// members of each struct ?
} // first braces, tell gcc we have a
// a struct as array member
}; // outer most braces, tell gcc we have
// an array
Now I have a function which prints the array content.
However, I don’t want to print all the array, because I’m only interested
in array elements who’s members are not empty. So I tried the following:
void printContacts( address * myContacts ){
printf("Inside printContacts");
int i = 0;
while ( i < 5 ) {
if (myContacts[i].cFirstName == NULL )
printf("%s", myContacts[i].cFirstName); //does not work
if (myContacts[i].cFirstName == '\0' )
printf("%s", myContacts[i].cFirstName); //does not work
if (myContacts[i].cFirstName[0] != 0 )
{
printf("%s", myContacts[i].cFirstName ); //does work!
}
i++;
}
}
So, my questions are:
- Am I initializing the array elements members to be really Null (e.g cFirstName[10]) ?
- Is there a better way ?
- How can I check that an array element member is empty ?
Thanks in advance for your answers!
What you have done in initializing your struct array could be improved upon.
The first brace says, “initialize the array with my contents:”
address myContacts[5] = { … }
The second set of braces says, “initialize the first struct in the array with the following:”
Note that it is good form to initialize all of your array elements at once, or to use
a for loop to do so. This is why your original initialization confuses me; I’m not sure it is “correct”, even if it runs.
Then, you put more braces inside of those (if you still want to do brace initialization for this application) to initialize the arrays in the struct:
That is the way to “zero out” your array first using bracket notation. Not too many people do it; it gets tedious. Usually, for a real application people would use the heap (memory that you can allocate on-the-fly, as shown below) for something like this, in which case you could simply use pointers in your struct:
You would then allocate a contacts list:
allocate strings when you need to add to the address book:
and when you’re done, free everything you’ve allocated:
This allows you to create variable-length strings, arbitrarily large contact lists, and if you want to check to see if an entry is empty, simply check to see if it’s pointer is null:
I hope this concept at least proves useful to you, even if you don’t end up using malloc (there are good reasons for or against using it in every program). 🙂