Home > front end >  What is the correct way to initialise pointers to structs in C ?
What is the correct way to initialise pointers to structs in C ?

Time:03-23

I am trying to learn the best practices while improving my C skills and I've got a question.

If I have, for example this, struct:

struct Vector {
    int x;
    int y;
};

typedef struct {
    Vector position;
    Vector velocity;
} Ball;

Which one would be the correct way to initialise it?

Ball* _ball1 = new Ball();
Ball* _ball2 = new Ball;

I know it would be better to create a class in this case, but I am trying to use all kinds of structures etc.

Also, regarding the struct definition - instead of typedef struct {} Ball;, would it be better just: struct Ball{}; ?

Any insight would be much appreciated.

Thanks!

Edit: Thank you everyone for the answers!

CodePudding user response:

First, you can do this:

Ball ball;

You now have a local Ball object. It will last until the enclosing code is closed. That is:

cout << "Foo\n";
if (true) {
    Ball ball;
}
cout << "Bar\n";

The ball exists only inside those {}. If you try to use it outside (where the cout of Bar is found), it won't be there. So in many cases, your variables will be alive for the scope of a function call.

void foo() {
   Ball ball;
   ...
}

This is the easiest thing to do, and it probably works for most of your use cases. You probably don't need to worry about pointers for your first pieces of code.

However, if there's a reason you want to really use pointers, you can do this:

void foo() {
    Ball * ball = new Ball;
    ... make use of it
    delete ball;
}

If you don't do the delete, you have a memory leak. Unlike Java, C doesn't have any sort of garbage collector. You're on your own.

But you can also do this:

void foo() {
    std::shared_ptr<Ball> ball = std::make_shared<Ball>();
    ... use it
    ... no delete required
}

These are referred to as smart pointers, and the trend in C is to use either unique_ptr or shared_ptr instead of raw pointers. (Raw pointers are what I did in the previous example.) These work more like C objects, where when you lose all the pointers, it knows and deletes the memory for you. This is referred to as RAII (Resource Acquisition Is Initialization), and you're strongly, strongly encouraged to learn it.

  • Related