In C, you cannot assign a value directly to an entire array, except during initialization (i.e. when declaring the object). Here is an example:
int main(void)
{
phonebook_record people[2] =
{
{ "my_name", "+555-000-0000" },
{ "my_name_2", "+555-000-0001" }
};
}
If you want to change the content of an null-terminated character array after the object has been declared, you can either assign values to the individual elements of the array (i.e. the individual characters), or you can for example use use the function strcpy
to change the content of several characters at once. Here is an example:
int main(void)
{
phonebook_record people[2];
strcpy( people[0].name, "my_name" );
strcpy( people[0].number, "+555-000-0000" );
}
However, using the function strcpy
can be dangerous, because if there is not enough space in the destination memory buffer, then you will have a buffer overflow. Therefore, it would generally be safer to use the function snprintf
instead, like this:
int main(void)
{
phonebook_record people[2];
snprintf(
people[0].name, sizeof people[0].name,
"%s", "my_name"
);
snprintf(
people[0].number, sizeof people[0].number,
"%s", "+555-000-0000"
);
}
Instead of overflowing the destination buffer, the function snprintf
will truncate the string, if it is too long. If you want to detect whether such a truncation happened, you can check the return value of snprintf
.
However, although it is not possible to assign a value to an entire array outside a declaration, it is possible to assign a value to an entire struct
. Since the two char
arrays are members of a struct
, assigning a value to the struct
will indirectly assign a value to the entire content of both arrays. One way to assign a value to a struct
is to assign it the value of a compound literal. Here is an example:
int main(void)
{
phonebook_record people[2];
people[0] = (phonebook_record) { "my_name", "+555-000-0000" };
}