I apologize if this might be viewed as a duplicate, but I cannot seem to find a conclusive answer that satisfies my question.
So I have a struct with a self referential pointer to pointers.
struct Node {
int id;
int edge_count;
struct Node **edges;
}
static struct Node s_graph[MAX_ID+1];
I then have a function that allocates some memory.
int add_edge(int tail, int head)
{
struct Node *ptail, *phead;
ptail = &s_graph[tail];
phead = &s_graph[head];
ptail->edges = realloc(ptail->edges, ++ptail->edge_count * sizeof(struct Node *));
if (ptail->edges) {
*(ptail->edges + ptail->edge_count - 1) = phead;
return 0;
}
return -1;
}
The above seems to work just fine. However, I keep seeing posts about pointer to pointers that lead me to wonder if I need to do something like the following in add_edge:
struct Node *phead = malloc(sizeof(struct Node *));
However, this does not seem logical. There should be enough memory for ptail->edges to store this pointer after the realloc call. I am fairly confident that I did the allocation correctly (albeit, inefficiently), but it is kind of sending me on a mind trip ... So when people declare pointer to pointers (e.g., **ptr) and then allocate memory for both ptr and *ptr, wouldn't that technically make ptr a pointer to pointers to pointers (and maybe clearer to declare as ***ptr)? Or maybe I am wrong and missing something conceptually?
Thank you in advance!
It depends on the situation, there is no general answer. If you have a pointer to pointer, eg Node**, and you want to store new data into it, then you need to have two levels of allocations, otherwise one is enough.
struct Node** nodes = calloc(AMOUNT, sizeof(struct Node*));
Now you have an array of struct Node* elements, so each element is a pointer to a struct Node.
Now how do you fill this array? You could want to insert new nodes inside it. Then you wouold require to allocate them, eg
nodes[0] = calloc(1, sizeof(struct Node)); // <- mind Node, not Node*
But in your situation you just want to set the address to an element of an array of the static variable s_graph, so you don't need to allocate a second level, you directly set the value.
So:
struct Node** nodes = calloc(AMOUNT, sizeof(struct Node*));
nodes -> | 0 | 1 | 2 | 3 |
nodes[0] = calloc(1, sizeof(struct Node))
nodes -> | 0 | 1 | 2 | 3 |
|
|
v
| NODE |
But if you have s_graph you already have them allocated, so it's something like:
static struct Node s_graph[MAX_ID+1];
struct Node** nodes = calloc(AMOUNT, sizeof(struct Node*));
nodes -> | 0 | 1 | 2 | 3 |
s_graph -> | N1 | N2 | N3 |
nodes[0] = &s_graph[0];
nodes -> | 0 | 1 | 2 | 3 |
|
|----|
v
s_graph -> | N1 | N2 | N3 |
Related
I'm working on cs50 pset5 speller, and in the lecture they introduce a new thing called nodes. What is a node? I didn't really understand what they said in the video. When I tried googling it, I got some sites that explained what a node is, but I didn't really understand. I'm new to c so I'm not accustomed to what I call 'coding words'. For instance, I found this on a site about nodes: A dynamic array can be extended by doubling the size but there is overhead associated with the operation of copying old data and freeing the memory associated with the old data structure. What is that supposed to mean? Please help me figure out what a node is because they seem important and useful, especially for pset5.
My node is defined like this:
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
Here is the link to the walk-through of speller pset5: https://cs50.harvard.edu/x/2020/psets/5/speller/
Node is a common terminology that is used to demonstrate a single block of linked list or tree or related data structures.
It is a convention to name it node, otherwise you can call it with any name.
Standard
C++
struct node{
int data;
int *next;
};
or in Python
class Node:
def __init__(self, data, next= None):
self.data = data
self.next = next
But you can call it with anyname
Not Standard
C++
struct my_own_name{
int data;
int *nextptr;
};
or in python
class my_own_name:
def __init__(self, data, next=None):
self.data = data
self.next = next
A "node" is a concept from graph theory. A graph consists of nodes (vertices) and edges that connect the nodes.
A node in C can be represented as a structure (a struct) that has all the necessary data elements "on board" to implement a graph. Optionally a structure may be required that represents the edges.
Example:
typedef struct NODE {
int node_id;
struct EDGE *edgelist;
} tNode;
typedef struct EDGE {
tNode *from, *to;
struct EDGE *next;
} tEdge;
Note: the term "node" may also be used in other contexts, for example the nodes of a binary tree, the nodes of a list, etc.
Expanding on Ahmad's answer, there are a number of data structures that are built of elements commonly called "nodes" - each node contains some data and some kind of reference (typically a pointer in C and C++) to one or more other nodes. For a singly-linked list, the node definition typically looks like
struct node {
data_t data; // for some arbitrary data_t type
struct node *next;
};
Each node contains the address of the following node. A graphical representation typically looks like
+------+------+ +------+------+ +------+------+
| data | next |------->| data | next |----->| data | next |------|||
+------+------+ +------+------+ +------+------+
You can also have doubly linked list, where each node points to both the preceding and following nodes:
struct node {
data_t data;
struct node *prev;
struct node *next;
};
And there are binary trees, where each node points to left and right child nodes:
struct node {
data_t data;
struct node *left;
struct node *right;
};
The use of the term "node" is just a common naming convention.
A dynamic array can be extended by doubling the size but there is overhead associated with the operation of copying old data and freeing the memory associated with the old data structure. What is that supposed to mean?
You can resize a dynamically allocated buffer using the realloc library function. For example, suppose we want to dynamically allocate a buffer to
store the string "foo". We'd write something like:
size_t bufsize = 4;
char *buffer = malloc( bufsize );
if ( buffer )
strcpy( buffer, "foo" );
We'll imagine the address returned from malloc is 0x1000:
+---+---+---+---+
0x1000: |'f'|'o'|'o'| 0 |
+---+---+---+---+
0x1004: | ? | ? | ? | ? |
+---+---+---+---+
... ... ... ...
Now, suppose we want to append the string "bar" to "foo". We didn't allocate a large enough buffer to do that, so we need to resize it using the realloc library function:
char *tmp = realloc( buffer, bufsize * 2 ); // double the buffer size
if ( tmp )
{
buffer = tmp;
bufsize *= 2;
strcat( buffer, "bar" );
}
else
{
// could not extend buffer, handle as appropriate
}
Now, if possible, realloc will just grab the space following the current buffer, so the result of that code would be:
+---+---+---+---+
0x1000: |'f'|'o'|'o'|'b'|
+---+---+---+---+
0x1004: |'a'|'r'| 0 | ? |
+---+---+---+---+
... ... ... ...
However, if the memory at 0x1004 had already been allocated for something else, then we can't do that. realloc will have to allocate a new buffer at a different address and copy the contents of the current buffer into it, then deallocate the original buffer. We'll imagine that the first region of free space large enough starts at 0x100c:
+---+---+---+---+
0x1000: |'f'|'o'|'o'| 0 |
+---+---+---+---+
0x1004: | ? | ? | ? | ? |
+---+---+---+---+
... ... ... ...
+---+---+---+---+
0x100c: | ? | ? | ? | ? |
+---+---+---+---+
0x1010: | ? | ? | ? | ? |
+---+---+---+---+
So realloc must first allocate the 8 bytes starting at 0x100c, then it must copy the contents of the current buffer to that new space:
+---+---+---+---+
0x1000: |'f'|'o'|'o'| 0 |
+---+---+---+---+
0x1004: | ? | ? | ? | ? |
+---+---+---+---+
... ... ... ...
+---+---+---+---+
0x100c: |'f'|'o'|'o'| 0 |
+---+---+---+---+
0x1010: | ? | ? | ? | ? |
+---+---+---+---+
and then finally release the space at 0x1000. We append "bar" to this new buffer, giving us:
+---+---+---+---+
0x1000: |'f'|'o'|'o'| 0 | // free'd memory is not overwritten
+---+---+---+---+
0x1004: | ? | ? | ? | ? |
+---+---+---+---+
... ... ... ...
+---+---+---+---+
0x100c: |'f'|'o'|'o'|'b'|
+---+---+---+---+
0x1010: |'a'|'r'| 0 | ? |
+---+---+---+---+
If realloc cannot find a large enough region to satisfy the request, it will return NULL and leave the current buffer in place. This is why we assign the return value of realloc to a different pointer variable - if we assigned that NULL back to buffer, then we'd lose our access to the original buffer.
A 'node' is not a C keyword.
The meaning of this:
A dynamic array can be extended by doubling the size but there is overhead associated with the operation of copying old data and freeing the memory associated with the old data structure
Dynamic allocation means that memory is allocated on the heap. The size of the memory space allocated does not have to be a compile time constant as in static memory allocation, and thus can be modified by reallocating more memory later on in the program's execution.
Overhead means the additional cost of doing an operation in comparison to some other way of doing the same operation. In this case increasing a dynamic array's size is an overhead in comparison with directly allocating the total required space.
I am trying to understand how pointers in linked lists work. So far i am having lots of trouble trying to figure out where the pointer is pointing to and how a pointer of a type struct works( I know we need to allocate memory from the heap but can't quite understand it, but maybe that's a different question altogether).
Lets take this structure:
typedef struct Node {
int data;
struct Node *link;
} Node;
What I think will happen now is:
Say you have a pointer of type Node in the main function, Node* p and this is allocated memory (using malloc).
Now if we have some data p->data=5; , p points to the beginning of this data (at least this is what i think is happening).
Where exactly does link point to?
So now, i come across this particular piece of code:
typedef struct Node {
int data;
struct Node *link;
} Node;
typedef struct List {
Node* head;
int number_of_nodes;
} List;
So this is complete chaos in my brain! .
Now in the structure List, what is head doing? What is it pointing to? And how would you create a linked list at all with these two lists??
I am really trying my level best to understand how linked lists work, but all the pointers make it too hard to keep track of. You might suggest i start with something simple and i did, and i have already mentioned how much i understand. But the head pointer in the second structure has completely thrown me off track!
It would make my life so much more easier if someone could help me explain it while keeping track of the pointers.
Where exactly does link point to?
link points to another object of the same type:
+------+------+ +------+------+ +------+------+
| data | link |---->| data | link |---->| data | link | ----> ...
+------+------+ +------+------+ +------+------+
Now in the structure List, what is head doing? What is it pointing to?
head points to the first node in a list:
+-----------------+ +------+------+ +------+------+
| head |---->| data | link |---->| data | link |----> ...
+-----------------+ +------+------+ +------+------+
| number_of_nodes |
+-----------------+
I am really trying my level best to understand how linked lists work,
Don't feel bad - linked lists threw me for a loop in my Data Structures class (my first "hard" CS class). It took me a solid week longer than my classmates to grok the concept. Hopefully the pictures help.
Edit
what happens if you have a pointer to the structure List, memory allocated and all? Where does it point to then (according to the diagrams, which did help by the way)
So, let's assume you have the following code:
/**
* Create a new list object. head is initially NULL,
* number_of_nodes initially 0.
*/
List *newList( void )
{
List *l = malloc( sizeof *l );
if ( l )
{
l->head = NULL;
l->number_of_nodes = 0;
}
return l;
}
int main( void )
{
List *l = newList();
...
}
Then your picture looks like this:
+---------+ +--------------------+
| l: addr | ----> | head: NULL |
+---------+ +--------------------+
| number_of_nodes: 0 |
+--------------------+
(addr represents some arbitrary memory address)
Now let's say you add a node to your list:
/**
* Create a new node object, using the input data
* link is initially NULL
*/
Node *newNode( int data )
{
Node *n = malloc( sizeof *n );
if ( n )
{
n->data = data;
n->link = NULL;
}
return n;
}
void insertNode( List *l, int data )
{
Node *n = newNode( data );
if ( n )
{
/**
* If list is initially empty, make this new node the head
* of the list. Otherwise, add the new node to the end of the
* list.
*/
if ( !l->head ) // or n->head == NULL
{
l->head = n;
}
else
{
/**
* cur initially points to the first element in the list.
* While the current element has a non-NULL link, follow
* that link.
*/
for ( Node *cur = l->head; cur->link != NULL; cur = cur->link )
; // empty loop body
cur->link = n;
}
l->number_of_nodes++;
}
}
int main( void )
{
List *l = newList();
insertNode( l, 5 );
...
}
Now your picture looks like this:
+---------+ +--------------------+ +------------+
| l: addr | ----> | head: addr | ---> | data: 5 |
+---------+ +--------------------+ +------------+
| number_of_nodes: 1 | | link: NULL |
+--------------------+ +------------+
You could add another node:
int main( void )
{
List *l = newList();
insertNode( l, 5 );
insertNode( l, 3 );
...
}
then your picture becomes
+---------+ +--------------------+ +------------+ +------------+
| l: addr | ----> | head: addr | ---> | data: 5 | +--> | data: 3 |
+---------+ +--------------------+ +------------+ | +------------+
| number_of_nodes: 2 | | link: addr | --+ | link: NULL |
+--------------------+ +------------+ +------------+
Naturally, you'd want to add some error checking and messages in case a node couldn't be allocated (it happens). And you'd probably want an ordered list, where elements are inserted in order (ascending, descending, whatever). But this should give you a flavor of how to build lists.
You'd also need functions to remove items and free that memory. Here's how I'd free an entire list:
void freeList( List *l )
{
Node *prev, *cur = l->head;
while( cur && cur->link )
{
prev = cur;
cur = cur->link;
free( prev );
}
free( cur );
}
int main( void )
{
List *l = newList();
...
freeList( l );
free( l );
...
}
… a pointer of a type struct…
A pointer cannot be of a type struct. A pointer can point to a structure.
C has objects. Objects include char, int, double, structures, and other things. A structure is a collection of objects grouped together.
In main, if you define p with Node *p;, you then have a pointer p. It has no value because you have not given it a value. When you execute p = malloc(sizeof *p);, you request enough memory for the size of the thing p points to (*p). If malloc returns a non-null pointer, then p points to a Node structure.
Then p->data refers to the data member of that structure. p->data is shorthand for (*p).data, in which *p means “the object p points to” and .data means “the data member in that object.”
After p = malloc(sizeof *p); and p->data = 5;, p->link does not point to anything because you have not assigned it a value. In a linked list, you would use malloc to get memory for another Node, and then you would set the p->link in one Node to point to the new Node. In each Node, its link member points to the next Node in the list. Except, in the last Node, p->link is set to a null pointer to indicate it is the last Node.
In List, you would set head to point to the first Node in a list of Node objects.
I have some questions regarding the definition of a linked list as it was defined in my class.
This is what was used:
typedef struct node_t {
int x;
struct node_t *next;
} *Node;
Now, I understand that this way we created a shorter way to use pointers to the struct node_t. Node will be used as struct node_t*.
Now, say we want to create a linked list. For example:
Node node1 = malloc(sizeof(*node1));
Node node2 = malloc(sizeof(*node2));
Node node3 = malloc(sizeof(*node3));
node1->x = 1;
node1->next = node2;
node2->x = 4;
node2->next = node3;
node3->x = 9;
node3->next = NULL;
This is roughly how I imagine this (The circles represent the structures):
Now I know it's wrong, but I can't understand why. We have a pointer, node1, that points to our structure. Then, we point at node2, which points at another structure and so and so on.
Another things is, I can't understand how is it possible to have the longer arrows in the picture. Shouldn't we only be able to point to a structure from each lower part of the circle, and not to a pointer to a structure? How is this possible?
If anyone here could make things a little clearer it would be hugely appreciated. Thank a lot.
You have three linked nodes, and additional local pointers pointing to them.
The nodes don't know anything about those local pointers though, even if it is often convenient to use their names to refer to the nodes.
Instead, they know the next node in the sequence, respectively the last node knows none.
Put another way, your image is flat-out wrong.
+---+------+
node1 --> | 1 | next |
+---+-|----+
|
v
+---+------+
node2 --> | 4 | next |
+---+-|----+
|
v
+---+------+
node3 --> | 9 | NULL |
+---+------+
Assignment is a transitive operation. So,
node1->next = node2;
would mean that node1->next points to whatever node2 was pointing to. And, in particular, node1->next does not point to node2 itself.
Each of node1, node2, and node3 name a variable that is a pointer.
node1 node2 node3
+---+ +---+ +---+
| * | | * | | * |
+ | + + | + + | +
v v v
+---+---+ +---+---+ +---+---+
| 1 | * --> | 4 | * --> | 9 | * --> NULL
+---+---+ +---+---+ +---+---+
typedef struct node_t {
int x;
struct node_t *next;
} *Node; /* <-- don't typedef pointers */
Simply use Node instead of Node * and then allocate with:
Node *node1 = malloc(sizeof(*node1));
Why? Somebody looking at your code 100 lines below the declaration of your typedef will not inherently know whether Node is a type, or whether it is a pointer-to-type. This type of confusion will only grow as your code grows in size. Review: Is it a good idea to typedef pointers?.
(note: good job using the dereferenced pointer to set the typesize in sizeof)
A Linked List
A linked list is simply a clever data structure that allows you to iterate over a number of independently allocated nodes. Each node contains some data and then a pointer to the next node in the list, or NULL if that node is the final node in the list.
(for a doubly-linked list, you simply add a prev pointer that also points to the node before the current node in the list. You also have circular lists where the last node points back to the first allowing iteration from any node to any other node in the list regardless of which node you begin iterating with. For a doubly-linked circular list, you can iterate the entire list in both directions from any node)
In your case, your list is simply:
node1 +-> node2 +-> node3
+------+ | +------+ | +------+
| data | | | data | | | data |
|------| | |------| | |------|
| next |--+ | next |--+ | next |---> NULL
+------+ +------+ +------+
Where your data is a single integer value and your next pointer simply holds the address of the next node in your list, or NULL if it is the final node in the list. Adding your data, your list would be:
node1 +-> node2 +-> node3
+------+ | +------+ | +------+
| 1 | | | 4 | | | 9 |
|------| | |------| | |------|
| next |--+ | next |--+ | next |---> NULL
+------+ +------+ +------+
When creating a list, the first node is usually referred to as the head of the list and the last node the tail of the list. You must always preserve a pointer to the head of your list as that pointer holds the beginning list-address. For efficient insertions into the list, it is also a good idea to keep a pointer to the tail node so you can simply insert the new node without iterating over the list to find the last node each time, e.g.:
Node *newnode = malloc(sizeof(*newnode)); /* allocate */
newnode->next = NULL; /* initialize next NULL */
tail->next = newnode; /* assign to tail */
tail = newnode; /* set new tail at newnode */
Lists are fundamental to C, there are many used in the Linux kernel itself. Take the time to understand them and how to write them in the differing variants. You'll be glad you did. Lastly, don't forget to write a simple function to free your list when you are done (and free the data as well if it is allocated). A simple free_list function would be:
void free_list (Node *list)
{
while (list) {
Node *victim = list; /* separate pointer to node to free */
list = list->next; /* can you see why you iterate next... */
free (victim); /* before you free the victim node? */
}
}
Let me know if you have further questions.
How is malloc being used in linked list generation? I do not see how it is being used to generate new linked lists, rather than reserve memory for linked lists
Tip: press Ctrl + F and look for "(***)" (without quotes) to find the exact code location
Example 1:
#include <stdio.h>
#include <stdlib.h>
struct LinkedList {
int data; /* The data part of the linked list */
struct LinkedList *next; /* The pointer part of the linked list */
};
int main(void) {
/* Generate the 1st node ("head") */
struct LinkedList *head /* I am not sure what this pointer */
head = NULL; /* is doing to the struct*/
head = malloc(sizeof(struct LinkedList)); /* Head points to null. Now
* malloc() is being called
* and is assigned to head.
* Next line implies head is
* already pointing to a
* linked list, which means
* malloc() is making a new
* strucuture (***) */
/* Generate the second node */
head -> data = 1; // This implies head is already pointing to a linked list
head -> next = malloc(sizeof(struct LinkedList));
/* Generate the third node */
head -> next -> data = 2;
head -> next -> next = malloc(sizeof(struct LinkedList));
/* Generate the fourth node */
head -> next -> next -> data = 3;
head -> next -> next -> next = NULL;
return 0;
}
Example 2:
#include<stdio.h>
#include<stdlib.h>
struct LinkedList {
int data;
struct LinkedList *next;
}; // notice the semi-colon!
int main(void) {
struct LinkedList *head = NULL; /* why is it doing this? */
struct LinkedList *second = NULL;
struct LinkedList *third = NULL;
// Generate the node structure:
/* how does (struct LinkedList*) affect malloc? (***) */
head = (struct LinkedList*)malloc(sizeof(struct LinkedList));
second = (struct LinkedList*)malloc(sizeof(struct LinkedList));
third = (struct LinkedList*)malloc(sizeof(struct LinkedList));
// Now fill the first node with info:
head->data = 1; /* assign data to the first node */
head->next = second; /* Link the first node ("head") with the second
* node ("second") */
// Now fill the second node with info:
second->data = 2; /* assign data to the second node */
second->next = third; /* Link the second node to the third node */
// Now fill the second node with info:
third->data = 3; /* assign data to the second node */
third->next = NULL; /* Since node 3 is our last node to the link list,
* we give it the value of NULL */
return 0;
}
The textbook describes a link list as being a chain structure. Malloc() is used for dynamic memory management. However, malloc is being used to declare a new structure in these examples and I do not understand why. I thought it only reserves memory
For example, in example 1, malloc() reserves the space for the structure, but does not "create" it (struct LinkedList var would create a new linked list and store it in var)
For example, in example 2, it looks like malloc() is being affected by (struct LinkedList*) (i.e. (struct LinkedList*)malloc(sizeof(struct LinkedList));), but I am unsure
You can look at linked list like on boxes connected with each other:
______ ______ ______
| data | | data | | data |
|______| |______| |______|
| next | | next | | next |
|______|----->|______|----->|______|----->NULL
Where each box is your:
struct LinkedList
{
int data; /* The data part of the linked list */
struct LinkedList *next; /* The pointer part of the linked list */
};
The size of your "boxes" (depends on arch) let's take x64 Linux machine is equal
to 16 bytes. To create linked list data type you need to store this boxes in memory (stack/heap) and connect them.
As I noticed the size is 16 byte for one "box" and it should be store in memory. For memory managment in userspace you can use malloc(), important thing here there malloc() is not "declare" anything it only allocate part of memory for your one "box" on the heap and you ask for exactly 16 bytes for your "box" using sizeof() operator.
struct LinkedList *head = malloc(sizeof(struct LinkedList));
It allocate memory for your "box" and now it look like this:
______
| data |
|______|
| next |
|______|----->NULL
When you do this:
head->next = malloc(sizeof(struct LinkedList));
Your allocate memory for another "box" and connect them:
______ ______
| data | | data |
|______| |______|
| next | | next |
|______|----->|______|
When you do this one:
struct LinkedList *head = malloc(sizeof(struct LinkedList));
struct LinkedList *second = malloc(sizeof(struct LinkedList));
struct LinkedList *third = malloc(sizeof(struct LinkedList));
You create three "boxes" somewhere in memory 16 bytes each. And they not connected for now, they only located in memory;
head second third
______ ______ _____
| data | | data | | data |
|______| |______| |______|
| next | | next | | next |
|______| |______| |______|
And you connected them doing this one:
head->next = second;
second->next = third;
third->next = NULL;
head second third
______ ______ ______
| data | | data | | data |
|______| |______| |______|
| next | | next | | next |
|______|----->|______|----->|______|----->NULL
Usually second approach used in function like for ex add_node_front()
void add_node_front(struct LinkedList **head_ref, int data)
{
/* 1. allocate node */
struct LinkedList *new_node = malloc(sizeof(struct LinkedList));
/* 2. put in the data */
new_node->a = data;
/* 3. Make next of new node as head */
new_node->next = (*head_ref);
/* 4. move the head to point to the new node */
(*head_ref) = new_node;
}
In the second example you also could allocate the memory statically:
struct LinkedList head;
struct LinkedList second;
struct LinkedList third;
Then you need to access with the dot-operator:
head.data = 1; //assign data to the first node
head.next = &second;
You could also use an array
struct LinkedList nodes[3];
node[0].data = 1;
node[0].next = &node[1];
and so on.
So, the malloc command is not essential to the concept of linked list.
But for many applications you do not know before, how big your linked list will be. And elements and the order will change during runtime. So, in this case the dynamic memory allocation with malloc/free is really helpful.
How is malloc being used in linked list generation?
malloc is used for allocating memory dynamically. When you are creating linked list, you can use malloc for allocating memory for the nodes of the list.
Read more about malloc here.
From Example 1:
head = malloc(sizeof(struct LinkedList));
From Example 2:
head = (struct LinkedList*)malloc(sizeof(struct LinkedList));
The only difference is, in Example 2, you are explicitly casting the malloc result. The malloc return type is void * and void * can be cast to the desired type, but there is no need to do so as it will be automatically converted. So the cast is not necessary. In fact, its not desirable to cast malloc return. Check this.
Your both the examples are functionally same except the memory allocation sequence.
In Example 1, you are allocating memory to head pointer and then to head -> next pointer and then to head -> next -> next pointer.
In Example 2, you are allocating memory to head, second and third pointer and later assigning second to head -> next and third to head -> next -> next.
Additional:
Always check the malloc return, like this:
head = malloc(sizeof(struct LinkedList));
if (NULL == head) {
fprintf (stderr, "Failed to allocate memory");
exit(EXIT_FAILURE);
}
Also, make sure to free the dynamically allocated memory once you are done with it. Follow good programming practice.
struct Node
{
int a;
struct Node *next;
};
How will next address point dynamically? I read malloc returns address value — is that right?
Please explain struct Node *next. Is this the default way of declaring a pointer in a struct?
If you have this declaration
struct Node
{
int a;
struct Node *next;
};
then you can define it like so:
struct Node node = {1, 0};
or
struct Node *node = (Node*) malloc(sizeof(struct Node));
When you want to attach a node to the next member then you can like so for example:
node.next = (Node*) malloc(sizeof(struct Node));
or
node->next = (Node*) malloc(sizeof(struct Node));
Example experiment:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
struct Node
{
int a;
struct Node *next;
};
struct Node node1;
struct Node *node2 = (Node*) malloc(sizeof(struct Node));
node1.a = 1;
node2->a = 2;
node1.next = node2;
node2->next = (Node*) malloc(sizeof(struct Node));
node2->next->a = 3;
printf("node1.a = %d, node1->next->a node2->a = %d, node2->next->a = %d\n", node1.a, node2->a, node2->next->a);
}
Yes your declaration is correct. To understand it, see it this way. When the compiler wants to know what kind of pointer it should compile the strcut's next field. The declaration type you gave is used. Since the compiler already parses the structure before coming to this line. It understands that the next pointer type is also of same structure type. I hope this helps in your understanding.
Start points to the top of the list and is available globally to your program. Whereas next just keeps track of the next item, and is available when referring to a specific 'node'. See this diagram it may help you understand with a visual!
link internally tracks the following item which keeps track of where the next component is as it is not necessarily contiguous the way arrays are.
+------+ +------+ +------+
| data | | data | | data |
+------+ +------+ +------+
| next |---->| next |---->| next |----> NULL
+------+ +------+ +------+
^
|
START (Keep track of the whole list.)
Hope that helps clarify.