I was going through the C lessons on structures and pointers and came across a quiz question with the following code:
The question wanted to know how to correctly initialize a structure variable of the myStruct type. All of the answers were defining the myName membership variable as a string (“bob”). I was a little bit confused as to how this could be correct. In the definition of the structure, the membership variables are an integer, a, and a pointer, myName, pointing towards a char type variable. How is it possible that we can correctly define this structure by setting the myName membership variable equal to a string instead of the pointer referencing the address of that string?
There is no
string type in C. So,
"bob" is, strictly speaking, an array of characters (
char). And an array in C is addressed by a pointer to its first element. Since
char, which is equivalent to
char*, we can use
I have not programmed in C for a long time, so I may be wrong in some details.
Sorry, I’m still a little bit confused. Wouldn’t that mean we are saying the character array is equivalent to the address its stored at?
I guess I would think that in the definition of the structure, we would have it read the following instead:
By removing the dereference operator it would then be okay to initialize a structure object of type myStruct and have the myName field populated by a string (character array).
I’m just confused as to why we are able to have the member variable char* myName and initialize that as a string (character array) when char* myName should be initialized with the address of of the myName array.