type casting

question
How can a struct be converted to a pointer when struct is 8 bytes(4 x 2) bytes and
a pointer is 4 bytes?
Thanks


1
2
3
4
5
6

  Struct node{
              int data;
              node* link;
}
  node* temp = (node*)malloc(sizeof(node))
It isn't isn't. Memory is allocated for the size of the struct and then its starting address is assigned to temp.
ok that makes sense
what typecast is used on right side of = sign?
A type of pointer-to-node ie an address that points to a memory location that contains data of type struct node.
new node() is same as malloc?
No, new is the C++ way of doing things*. It calls the constructor of an object and will correctly initialize its state, no matter how complex. malloc simply allocates raw memory, and the caller must know what else needs to be done initialize the object.

*even better would be to avoid the use of new or malloc in the first place in C++. But for a learning exercise like a linked list, using new is fine imo.
Last edited on
(node*)malloc(sizeof(node)) initializes memory for both data and link within struct. Why is onlyaddress of new allocated memory inserted in node* temp not int data ?
"A type of pointer-to-node ie an address that points to a memory location that contains data of type struct node."
thanks seeplus
malloc(sizeof(node)) allocates sizeof(node) bytes. It does not initialize anything. I'm not sure what your second sentence means.

I should be more specific, calling Node* node = new Node; here also would not initialize data and link to any particular value. If you had a constructor like node() : data(0), link(nullptr) { }, then both data and link would be initialized to 0/nullptr, respectively, when you call new.
starting to make sense
malloc(sizeof(node))returns a void pointer with address of new memory block. Why does (node*) precede malloc(sizeof(node))?
The (node*) part is a cast to interpret the pointer as pointing to a node object, as opposed to just being a generic address, pointing to something of unknown size (which you can't dereference). It doesn't change the data itself.
Topic archived. No new replies allowed.