StackMeta_t *mystack_create(size_t objsize)
{
StackMeta_t *elem;
elem = (StackMeta_t*)malloc(sizeof(StackMeta_t));
if(elem == NULL)
{
return NULL;
}
else
{
elem->stack = NULL; // my actual stack basically the first elem(the top)
elem->objsize = objsize; // size of the datatype
elem->numelem = 0; // total count of elem inside the stack
}
return elem;
}
//PUSH
int mystack_push(StackMeta_t *data_stack, void* obj)
{
if(data_stack == NULL)
{
return -1;
}
StackObject_t *nodeObject = NULL;
nodeObject = (StackObject_t*)malloc(sizeof(StackObject_t));
if(nodeObject == NULL)
{
return -1;
}
nodeObject->obj = malloc(data_stack->objsize);
if(data_stack->stack == NULL)
{
nodeObject->next = NULL;
}
else
{
nodeObject->next = data_stack->stack;
}
memcpy(nodeObject->obj, obj, data_stack->objsize);
data_stack->stack = nodeObject;
data_stack->numelem++;
return 0;
}
So I am trying to translate my C code into C++ code. These are Linked List and Stacks data structure
I researched that the malloc() version of C++ is the new
keyword. So creating memory for the
linked list nodeObject
, I did StackObject_t *nodeObject = new StackObject_t;
.
But the problem I encountered is creating memory for the obj
of the Linked List. The data type for this variable is void* obj;
. So that would be using a pointer to the objsize
created with by the mystack_create(size_t objsize)
function.
My question is, how do I convert nodeObject->obj = malloc(data_stack->objsize);
to C++ while using the new
keyword?
I tried doing nodeObject->obj = new data_stack->objsize;
and the error gives me expected a type specifier
. Do I need to cast data_stack->objsize
? and what is the syntax for this for future reference? I have been coding with C for almost a year now and I know a few OOP from C#. Now I am just beginning to learn C++ and I couldn't find any answer for this type of situation.