I'm having trouble understanding pointers with nodes and arrays. assume we have this structure:
typedef struct node
{
int x;
struct node *next;
}node;
if I have an array of node pointers like:
node *table[50];
can I say:
table[0] = malloc(26 * sizeof(node*));
is it possible?
I mean table[0] is a pointer to a node but malloc will return a pointer to a pointer of a node.
In fact, I want to make more than one (for each pointer in the new array I want to create a new array of node pointers and at last each element of the last array will have a linked list)
Hope I was clear and excuse me for my bad English.
malloc is allocate space for your data.
table = (node*)malloc(50 * sizeof(node));
now table is a pointer to a space in memory that can store 50 node.
then you can use this as an array:
table[n]
Related
In creating a linked list we make a node structure and it consists of both data and a pointer to the next node. Later when we make a function to append elements onto the linked list, we make a temporary node to store the inputted data.
Let’s consider the following program-
#include<stdio.h>
struct node
{
int data;
struct node* link;
}
struct node* root=NULL;
void main(append)
{
struct node* temp;
temp= (struct node*)malloc(sizeof(struct node))
.....
}
My first question set:
In line 11, why do we need to mention (struct node*) before the malloc function?
What is the significance of that?
My second question set:
If we are making a doubly linked list which would have a node structure consisting of 2 pointers (for next and previous node), would we also initialize a pointer (for traversing the list) of the struct node type?
Is there a different way to initialize the pointer in that case?
The significance is to make bugs in your program,
The malloc will return void* and when you assign to your struct somthing* it will convert automaticlly.
You simply don't cast the result of malloc as it returns void* . There is one fine explanation here
A better solution might be :
struct node *temp;
temp = malloc(sizeof *temp);
why do we need to mention '(struct node*)' before the malloc function,
what is the significance of that?
By writing (struct node*) before the malloc function, you are type-casting the return value to the specified type. The cast here is optional and often frowned upon.
if we are making a doubly linked list which would have a node
structure consisting of 2 pointers(...
When making a doubly linked list, you should declare something like:
struct node {
int data;
struct node *next;
struct node *previous;
};
You can allocate space for a node by using the malloc function. The next and previous pointers are again pointers to struct nodes. Call malloc again to allocate space for the next element. For the first node, the previous should be NULL and for the last node, next should be NULL. Here is one implementation.
This is the because the return type of malloc is void*. (struct node*) is a cast using which you tell the compiler that you want to treat the value returned by malloc as a pointer to struct node.
For double linked list you can use,
struct node
{
int data;
struct node *next,*prev;
};
int main()
{
struct node *new_node=(struct node *)malloc(sizeof(node));
}
malloc returns the void pointer(can be checked and verified at the header ), and so the type casting is necessary while assigning it to the other type of variable.
Request you to read at the link https://www.tutorialspoint.com/cprogramming/c_type_casting.htm
Hi guys I'm new to linked lists, but I'm pretty sure that I know how they work, theoretically, I think I might having a syntax misunderstanding, or memory management error.
edit: My main purpose is to make a collection of lists which are indexed by the array, each array element is a head(or root) node. I'm having issues allocation dynamically this struct array.
What I'm doing is the following:
typedef struct item_list{
int item_name;
int item_supplier;
int item_price;
struct item_list *next
}node;
int i;
node ** shop_1 = (node **)malloc(shop_items_elements * sizeof(node));
for (i=0;i<=shop_items_elements;i++)
{
shop_1[i]->next=NULL;
}
I'm getting a segmentation fault while I try to give next at the element i the value of NULL.
The problem is that you are trying to allocate the memory for 20000 items as a contiguous block. Which implies that you actually haven't understood linked lists yet.
I think you are mixing up random access array functionality with pure linked lists which do not allow accessing individual items without traversing the list.
A linked list usually has a head and tail node which are initially NULL when there are no elements in the list:
node* head = NULL;
node* tail = NULL;
When adding a new node you first allocate it by using malloc with the size of a single node struct:
node* the_new_node = (node*)malloc(sizeof(node));
Initialize the struct members, specifically set next to NULL for each new node. Then use this append_node() function to append the node to the linked list:
void append_node(node** head, node** tail, node* the_new_node)
{
if(*tail == NULL)
{ // list was empty
*head = *tail = the_new_node;
}
else
{
(*tail)->next = the_new_node; // link previous tail node with new one
*tail = the_new_node; // set the tail pointer to the new node
}
Please note the pointer to pointers which are needed to update the head and tail pointers. Call the function like this for any given n you want to add:
append_node(&head, &tail, n);
Repeat this for every new node.
A much better way of encapsulating a linked list is putting the head and tail pointers into another struct
typedef struct linked_list
{
node* head;
node* tail;
} list;
and using an instance of that as first argument to append_node() (which I'll leave to you as an exercise ;)
When using such a linked list it is not possible to conveniently access the Nth node in less than O(n) since you have to follow all next pointers starting from the head node until you arrive at the Nth node.
EDIT: If you want to have the possibility to index the shop items and build a linked list from each of the elements I would suggest the following solution:
node** shop_1 = (node**)malloc(shop_items_elements * sizeof(node*));
int i;
for(i = 0; i < shop_items_elements; ++i)
{
node* n = (node*)malloc(sizeof(node));
n->next = NULL;
shop_1[i] = n;
}
You first allocate an array of pointers to node pointers which have to be allocated individually of course. Take a look at this diagram for reference:
The actual node instances may be larger than a pointer's size (unlike drawn in the diagram) which is the reason why you allocate N * sizeof(node*) in a block instead of N * sizeof(node).
Your code needs to look like this
int i;
node * shop_1 = (node *)malloc(shop_items_elements * sizeof(node));
for (i=0;i<shop_items_elements;++i)
{
shop_1[i].next=NULL;
}
Your malloc statement has allocated an array of nodes, not an array of pointers to nodes. (If that is what you wanted instead, then you would have had to initialize each pointer with a further malloc call before trying to assign a value to a field within the node pointed to.)
I'm making a Binary Tree as a part of my homework.
This is the given struct:
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
}
My build_tree function is recursive, and this is the prototype:
void build_tree(TreeNode** root, const int elements[], const int count);
The homework is meant to partly test dynamically allocated memory. So my problem keeps happening when I try to assign a value to one of the pointers inside the struct. I have seen questions similar to this, but it never seems to be this question exactly, but still involves structs and pointers. If I misunderstood, I apologize for duplicating questions.
The build_tree method has to be done recursively
This is my code for when an element should be inserted to the right of the root:
if(elements[0] > (*root)->data){
TreeNode newnode = {elements[0], NULL, NULL}; //make a node to add
*((*root)->right) = newnode; //dereference the root.right pointer, and set to newnode (GIVES COMPILE ERROR HERE)
struct TreeNode **rightptrptr = malloc(sizeof((*root)->right)); //allocate a pointer to a pointer
*rightptrptr = (*root)->right; //dereference pointer to a pointer, assign to root.right pointer
build_tree(rightptrptr, new_elems, count - 1);
}
If it's important, the root node has been initialized to {an integer, NULL, NULL}.
My understanding of pointers isn't all that sophisticated, so please forgive me if this code is horrendous.
There are many issues here, I'll try to point them out:
TreeNode newnode = {elements[0], NULL, NULL};, this allocates the struct on the stack, which means that the address of newnode (&newnode) won't be valid anymore when exiting the scope of the function.
if you need to build the tree by dynamically allocating the nodes TreeNode newnode = {elements[0], NULL, NULL} is not what you are looking for. This is not a dynamically allocated object, it's on the stack and the only thing you can do it with it to copy the content to an allocated node. You need always to allocate TreeNode* node = calloc(sizeof(TreeNode)) in your situation
((*root)->right) = newnode, here you dereference the pointer to assign newnode to it. It could work but only if right points to allocated memory, which is not the case since your root initializes it to NULL. You should instead allocate directly the pointer, eg root->right = calloc(sizeof(TreeNode))
struct TreeNode **rightptrptr = malloc(sizeof((*root)->right)), here you allocate a pointer to a pointer to a TreeNode because the recursive function expects this but your approach is wrong. You should pass the pointer to an existing subtree, not allocating one with no purpose, you can do it by doing, for example &root->right.
0i have declared a struct as follows:
struct node
{
int num;
struct node *ptr;
};
typedef struct node NODE;
and i have a linked list with a pointer called first pointing to it.
and i have also declared an arraye of the above type NODE NODE* array[312500];
and now i want to make array[0] point to the linked list instead of first, so i have used array[0]->ptr=first;
but this way gives me a segmentaion fault!!! what might be the problem!!!
You declared an array of pointers, but never allocated memory for any of the pointers.
NODE* array[312500];
Is an array of 312500 pointers of type NODE*
If you wanted just NODEs, then say
NODE array[312500];
Else, you will need to say something like
array[0] = (NODE*) malloc(sizeof(NODE));
And then you can alter its ptr
You forgot to allocate memory to the array.
You just have an array of pointers.So array[0]->ptr will give a segmentation fault.
Allocate memory to the array first :
for(i=0;i<312500;++i)
{
array[i]=(NODE*) malloc(sizeof(NODE));
}
Or at least to array[0] by the same syntax to use array[0]->ptr.
I have a two struct, one is linked list.
typedef struct Mark{
int people;
Node *nodeyy;
}Mark
typedef struct Node{
struct node next;
int value;
}Node
if i allocated memory for a node, let say
Node *node1=malloc( sizeof(struct Node));
And I also allocated memory for a bookmark, let say
Mark *mark1=malloc( sizeof(struct Mark));
I want to make the pointer nodeyy in the mark1 points to the same thing as node1, how can i do that?
I think that
mark1->nodeyy=node1;
is definitely wrong.
change the int* in struct Mark to Node*
typedef struct Mark{
int people;
Node *nodeyy;
}Mark
then you can do
mark -> nodeyy = (Node *) malloc(sizeof(Node))
its correct now:
You will have to initialize the pointer or point it to an existing variable that you know won't go out-of-scope. BUT since node1 is dynamically allocated, you're just assigning one pointer to another, this creates a sort of reference to the newly allocated memory pointed by node1.
mark1->nodeyy = node1;
After this statement, mark1->nodeyy and node1 point to the memory location returned by the malloc(sizeof(Node)).