Why can't I initialize the integer variable num
with the value of the number
field of the Strct
structure?
#include <iostream>
struct Strct
{
float number = 16.0f;
};
int main()
{
Strct* strct;
int num = strct->number;
return 0;
}
Error List: C4700 uninitialized local variable 'strct' used
CodePudding user response:
Why can't I initialize the integer variable num with the value of the number field of the Strct structure?
Because the pointer is uninitialised, and thus it doesn't point to any object. Indirecting through the pointer, or even reading the value of the pointer result in undefined behaviour.
I thought my strct points to the Strct structure, that is, to its type
No. Pointers don't point to types. Object pointers point to objects. Types are not objects in C .
16.0f is not the value of number
. 16.0f is the default member initialiser of that member. If you create an object of type Strct
, and you don't provide an initialiser for that member, then the default member initialiser will be used to initialise the member of the object in question.
then can I define a member function that returns the address of this structure?
A structure is a type. A type isn't stored in an address. There is no such thing as "address of a type".
Here is an example of how to create a variable that names an instance of the class Strct
:
Strct strct;
You can access the member of this variable using the member access operator:
int num = strct.number;
Here is an example of how to create an instance that doesn't use the default member initialiser:
Strct strct = {
.number = 4.2f,
};