arrays of type struct - c

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.

Related

node pointer to point to an array of node pointers

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]

Linked list node memory allocation

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

Homework, Assigning pointers within a struct in C

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.

Assign variable to struct member

I have created a struct with a char variable in it. I want to assign a string value to it when using it inside of a method and then print it. I have been looking around but can't find a valid answer, but can't find what I'm doing wrong. Why am I getting the error below?
Here is what I have tried:
struct node{
char *val;
struct node *first;
struct node *last;
};
void main(){
struct node *new_node;
new_node =(struct node *)malloc(sizeof(struct node));
new_node.val = "a";
printf("%s",new_node.val);
}
I get the error:
request for member 'val' in something not a structure or union
new_node should be accessed as a pointer and not an instance.
try new_node->val instead of new_node.val
response to edited question
As you have changed from char val to char *val you will need additional processing:
allocate memory for *val : new_node->val=(char*)malloc(sizeof(char))
assignment will need to dereference the pointer : *(new_node->val)="a"
Print statement should also dereference the pointer : printf("%c",*(new_node->val))
you should free the val pointer before freeing new_node: free(new_node->val)
new_node.val should be replaced with new_node->val. since new_node is a pointer. Keep in mind that new_node->val (often refereed as the arrow operator) is the shorthand for (*new_node).val.
Also i believe you can write:
node *new_node = malloc(sizeof(node));
For easier reading and cleaner code since malloc will just return a pointer to a given memory address. Use -Wall or other warning flags when you compilate your program to experience less logical errors or seg faults.

how to use a pointer inside struct in C

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)).

Resources