I've created a structure with three attributes of a planet. Then, I've created a function which creates a new planet - it's part of a larger application, but it's just a function that assigns the function parameters to some struct variables, then return the structure.
It's actually a snippet of code that I'm trying to understand better. I'm trying to grasp the concept of pointers and dynamic memory.
#include <iostream>
#include <string.h>
using namespace std;
typedef enum {
NEPTUNE_LIKE,
GAS_GIANT,
TERRESTRIAL,
SUPER_EARTH,
UNKNOWN
}PlanetType;
typedef struct {
char name[30];
PlanetType type;
float distanceToEarth;
}Planet;
Planet createPlanet(char myname[], PlanetType mytype, double mydistance)
{
Planet pl;
strcpy_s(pl.name, myname);
pl.type = mytype;
pl.distanceToEarth = mydistance;
return pl;
}
char* getName(Planet* p)
{
return p->name;
}
PlanetType getType(Planet* p)
{
return p->type;
}
double getDistance(Planet* p)
{
return p->distanceToEarth;
}
int main()
{
char s[30] = "Nume";
static Planet* pl = new Planet();
*pl = createPlanet(s, UNKNOWN, 345);
cout << getType(pl) << endl;
return 0;
}
My question is: what's the purpose of static Planet* pl = new Planet()
and why doesn't the program run without it? How is it possible to have a variable pl
that points to an entire function? I see the logic behind why a variable would point to an integer for example, but I can't understand what happens in the above case.