- #1
nobahar
- 497
- 2
Hello,
Another (probably obvious) question:
malloc() assigns memory space in bytes; e.g. malloc(100) assigns 100 bytes of space and returns a pointer.
However, in creating a linked list, I can allocate space a assign it to a pointer and the structure already exists?
For example:
If malloc() only assigned space in memory, then why does head->h_ptr = NULL work? malloc() set aside the correct amount of space, but it doesn't "know" what for, the structure type hasn't been placed there. Does the pointer type - that malloc is set to point to a structure of type happy - mean that the structure type is created because of the pointer? I have seen typecasts, e.g. head = (struct happy *)malloc(sizeof(struct happy)), used, but also read that they are not necessary in C. If the typecast was used, I can imagine that it tells the malloc() function to "divide up" the space into a happy structure type; does the pointer type, by pointing to a happy structure type, do the same thing?
Any help appreciated,
Thanks in advance.
Another (probably obvious) question:
malloc() assigns memory space in bytes; e.g. malloc(100) assigns 100 bytes of space and returns a pointer.
However, in creating a linked list, I can allocate space a assign it to a pointer and the structure already exists?
For example:
Code:
//Create structure
struct happy
{
int x;
struct happy *h_ptr;
};
int main( void )
{
//Pointers for assigning head to link to first structure and a pointer for creating new links
struct happy *head = NULL;
struct happy *newlink = NULL;
//Assign memory for structure and assign address of space to head pointer
head = malloc(sizeof(struct happy));
//Make the pointer in happy, h_ptr, point to NULL, since it is the last (and only) element
head->h_ptr = NULL;
...
return 0;
}
If malloc() only assigned space in memory, then why does head->h_ptr = NULL work? malloc() set aside the correct amount of space, but it doesn't "know" what for, the structure type hasn't been placed there. Does the pointer type - that malloc is set to point to a structure of type happy - mean that the structure type is created because of the pointer? I have seen typecasts, e.g. head = (struct happy *)malloc(sizeof(struct happy)), used, but also read that they are not necessary in C. If the typecast was used, I can imagine that it tells the malloc() function to "divide up" the space into a happy structure type; does the pointer type, by pointing to a happy structure type, do the same thing?
Any help appreciated,
Thanks in advance.