I am beginner in c++. Here is my doubt why in this program they are again creating struct variable from the previously created struct object ? Here is the example:
typedef struct prog1
{
int a,b;
}*obj1;
int main()
{
obj1 moc=new prog1(); // why again creating object for *obj1 object?
moc->a=10; // why dont we use obj1 -> a=10;
}
thanks
obj1
is not an object but a type definition, because it is part of the typedef
definition. Namely, it is a type of prog1*
(a pointer to prog1
). The obj1 moc
declares a variable of this type, ie moc
is a pointer to prog1
.
To make it more clear use an alias declaration instead of the typedef definition.
struct prog1
{
int a,b;
};
using obj = struct prog1 *;
So the name obj
is an alias for the type struct prog1 *
. obj
is not a variable.
So in this declaration
obj1 moc;
there is defined the variable moc
with the type obj
. This declaration is equivalent to the following declaration
prog1 *moc;
That is there is declared a pointer of the type prog1 *
.
Pay attention to that the pointer is not initialized. So it has indeterminate value. As a result the following statement
moc->a=10;
invokes undefined behavior.
you don't need to use typedef
before struct. you can directly use prog1 as a type. like this:
struct prog1 {
int a,b;
} obj1; //<---create right away the obj1.
int main() {
prog1 obj2; //<---another object created.
prog1 *pObj = new prog1();
obj1.a = 10;
obj2.a = 20;
pObj->a = 30;
//...
}
or you don't even need the prog1
struct name. like this:
struct {
int a,b;
} obj1, obj2, *pObj; //<---obj1 and obj2 already has allocated space for data.
int main() {
pObj = new prog1(); //<---allocate data space that will be pointed by pObj.
obj1.a = 10;
obj2.a = 20;
pObj->a = 30;
//...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.