type casting

Feb 18, 2021 at 5:50pm
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))
Feb 18, 2021 at 5:53pm
It isn't isn't. Memory is allocated for the size of the struct and then its starting address is assigned to temp.
Feb 18, 2021 at 6:01pm
ok that makes sense
what typecast is used on right side of = sign?
Feb 18, 2021 at 6:03pm
A type of pointer-to-node ie an address that points to a memory location that contains data of type struct node.
Feb 18, 2021 at 6:07pm
new node() is same as malloc?
Feb 18, 2021 at 6:19pm
No, new is the Python 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 Python. But for a learning exercise like a linked list, using new is fine imo.
Last edited on Feb 18, 2021 at 6:21pm
Feb 18, 2021 at 6:43pm
(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 ?
Feb 18, 2021 at 6:47pm
"A type of pointer-to-node ie an address that points to a memory location that contains data of type struct node."
thanks seeplus
Feb 18, 2021 at 6:51pm
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.
Feb 18, 2021 at 7:17pm
starting to make sense
malloc(sizeof(node))returns a void pointer with address of new memory block. Why does (node*) precede malloc(sizeof(node))?
Feb 18, 2021 at 8:24pm
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.