user1220022 user1220022 - 2 months ago 6
C Question

Converting link list from C to C++

I have a working linked list implementation in C (from linux) which I want to convert for use in C++ (on windows).

I have a player struct, which looks like this:

typedef struct PLAYER {
char * name;
struct PLAYER * next;
} player;


In my original C code, I initialised the player list like this:

player * player_list;
player_list = malloc(sizeof(player));


However, for use in C, I cannot use (void *), so I need to cast it like this:

player * player_list;
player_list = (player*)malloc(sizeof(player));


For usage of adding/linking players, I check whether items in the linked list are set to
NULL
, however after some debugging I can see that in C++ the malloc'ed data is not set to
NULL
like it is in C.

For example, in the C implementation
current->next == NULL
is true, while in C++ it is false.

My question is, how do I malloc data in C++ so the data is set to be
NULL
by default? Thereby permitting me to use my original functions.

Answer

If you need to make a linked list in C++, you should use operator new for allocating memory and you don't need typedef.

struct Node
{
  std::string name;
  Node * next;
};

// creating a new node
Node * p_node = new Node;
Node.name = "John";
Node.next = nullptr;

Note the change from char[] to std::string. The std::string type should be used for text since it handles allocation and deallocation for the text content.

Also, you'll eventually want to use template so that you can apply the linked list data structure to different node types.

Or you can simplify your life and use std::list, as in:

std::list<name> name_database;