C(++) malloc confusion

arrays, c++, malloc

Solution

Use vector to do the job.

#include <vector>

typedef struct
{
int x;
int y;
} Coordinate;

std::vector<Coordinate> coordinates;

Coordinate newCoord;
newCoord.x = 1;
newCoord.y = 1;

coordinates.push_back(newCoord);

Additional Information: To understand malloc/free and new/delete you might read chapter

13: Dynamic Object Creation

in Bruce Eckels Thinking C++ Volume 1. Its a book that can be downloaded for free.

Problem

I'm just not getting any further with allocating memory for arrays in C and mainly C++. I've looked for examples but there aren't any useful ones for me out there, at least it seems so. So if I have a typedef here like this: ``` typedef struct { int x; int y; } Coordinate; Coordinate* myList; ``` And I have an array of the type `Coordinate` too, how do I append items to it dynamically. All I know is that I have to use `malloc` and later `free` in C and `new` / `delete` in C++. (Malloc scares the hell out of me) So what I was aiming for is a function like this: ``` void AddSomething ( int x, int y ) { // myList malloc/new magic here } ``` My question is: How does the line that allocates new memory for myList and then adds the new item to it have to look like? Could you please show me a working example for C and C++? How exactly does malloc in C work? There are some things about it that I'm not familiar with (there is some sort of pointer before the function, and the variable that is allocated is set to `malloc`s return value)

Original source