I'm learning how to use structures in C. But in the following code I couldn't print myArray "HELLO!" which is declared as a char array:
#include <stdio.h>
struct myStruct
{
int myInt;
float myFloat;
char myArray[40];
};
int main()
{
struct myStruct p1;
p1.myInt = 80;
p1.myFloat = 3.14;
printf("Integer: %d\n", p1.myInt);
printf("Float: %f\n", p1.myFloat);
p1.myArray = "HELLO!";
printf("Array: %s\n", p1.myArray);
return 0;
}
What is wrong in the above syntax that I don't get "HELLO!" as an output? Something wrong here:
p1.myArray = "HELLO!";
printf("Array: %s\n", p1.myArray);
Arrays are non-modifiable lvalues. So this attempt to assign a pointer (the string literal is implicitly converted to a pointer to its first element) to an array designator
will not compile.
Either use the standard string function
strcpy
as for exampleOr you could initialize the data member initially when the object of the structure type is defined as for example
or
or
or
Here is a demonstrative program.
The program output is