There exists a structure I defined as follows:
struct details
{
char name[20];
int age;
char country[20];
};
In this specific instance, however, declaring an object of the structure and assigning a string literal as value to either of the two character array members yields an error. The error erupts when I assign values through the following way:
int main()
{
struct details d1;
d1.name="Constantine";
d1.country="Byzantium";
exit(EXIT_SUCCESS);
}
The error that my GCC C compiler yields is as follows:
error: incompatible types in assignment of 'const char [12]' to 'char [20]'
Does this occur owing to the fact that the string literal is a constant character array whereas the character array members I have declared as constituents of the said structure are not constant in nature? Would declaring the said structure members as constant resolve the error at hand? Or do I have embrace a different approach to load initial values to the said structure members?
In C language =
does not copy the context of the arrays. String literal is a const char
array. To copy arrays you need to iterate through all elements of the arrays.
char *copy_string(char *dest, const char *src)
{
char *wrk = dest;
while((*wrk++ = *src++)) {}
return dest;
}
As string manipulations are very common in the programming C standard library provides string manipulation functions (strcpy
, strlen
, strcmp
etc etc) 'out of the box'
You can only use the assignment when you initialize the object. During the initialisation, the string literal will be copied into the array.
struct details d1 = {.name="Constantine", .country="Byzantium"};
char str[] = "Hello World";
int arr[] = {0,1,2,3,4,5,6,7,8,9,10};