struct node {
int data;
struct node *next,*prev;
};
void insert(struct node *head,int data){
if(head == NULL){
head = (node *)malloc(sizeof(node));
--- code continues-----
I just want to know the difference between
head = (node *)malloc(sizeof(node)); and struct node *head = malloc(sizeof(struct node));
And if I pass **head as a parameter of the insert function what does it do ?
The difference between:
head = (node *)malloc(sizeof(node));
struct node *head = malloc(sizeof(struct node));
is that a C compiler will reject the first and allow the second, but a C++ compiler will accept the first and reject the second.
In C, the code shown does not create a type name node when you define or declare struct node. You would need to add typedef struct node node; in the C source. C++ automatically creates the type name node from the definition of struct node. (A C++ compiler rejects the second because of the implicit cast from void * to struct node *; C++ does not allow that, and would require struct node *head = (struct node *)malloc(sizeof(struct node));)
And if I pass **head as a parameter of the insert function, what does it do?
You'd have to adjust the body of the function, but it would allow you to change the location of the head of the list in the calling function.
The answer for your first question is:
head=(node *)malloc(sizeof(node));
malloc() returns a pointer of type void so here you are explicitly converting it to a pointer of type node .But remember, in C a pointer of type void() converts implicitly into the type of pointer that it is assign to. So if you write like:
head=malloc(sizeof(node));
It will stil work correctly. But with the C++ compiler it is not the case, In C++ pointer of type void is not implicitly cast to the type of pointer that it it assign to.
Also to answer your question,
void insert(struct node *head,int data)
If you pass **head as parameter it will show an error declaring that the type of operator is not matched. This is because you had declared it as struct node *head not as struct node **head.
If you type in
typedef struct node{
int data;
struct node *next, *prev;
} node;
the compiler will accept your head = (node *)malloc(sizeof(node)); code. Remember that typedef allows you to use the struct the same way it's used in C++.
Technically there isn't a difference between sizeof(node) and sizeof(struct node) (at least in C++), since both will return the size of the struct.
In C however it's mandatory to write struct node, just like it's mandatory to write struct node when declaring a variable of that type, simply because there is no type node.
C only understands primitives (int, char, long) and custom types declared with struct. Every C compiler is very strict with this keyword struct and assumes you're talking about a variable if you forget it.
Regarding your second question: You can't. You can't pass a pointer to a pointer to a function, which only accepts a regular pointer, unless you cast it. In that case however, it will point to a completely arbitrary position on the stack (where your pointer is located) and probably make your program crash.
create (struct node **p)
{
struct node *temp,*q;
int n;
printf("enter the length of link list");
scanf("%d".&n);
while(n>0)
{
if(*p == NULL)
{
*p=(struct node*)malloc(sizeof(struct node*));
printf("enter the element");
scanf("%d".&((*p)->data));
(*p)->next=NULL;
}
else
q=*p;
while(q->next=NULL)
q=q->next;
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
I'm working with linked lists. I'm having trouble accessing the data contained in a struct through a pointer. Here is my code:
void insertNode(Node **head, int num) {
Node *newNode = malloc(sizeof(Node));
newNode -> num = num;
while (head->next) { <-----problematic code
}
}
I've passed the address of the head pointer of the list into the function.
Node *list = malloc(arraySize * sizeof(Node));
Node *head = list;
insertNode(&head, randNum);
I keep getting an error that says "request for member "next" in something not a structure or union.
Node **head is a pointer to a pointer to a Node. So head-> is dereferencing a pointer to a pointer and therefore gives you a pointer. A pointer is not a struct or union, hence the error. You can use:
(*head)->
to dereference the underlying node.
Try (*head)->next in your loop.
Reason is simple, you send Node** but expect that it will work like a Node*, which is not correct.
Can someone please explain why am I getting the compilation error the below code.
Error says:
"expected unqualified-id before 'struct' " on line number 7 ".
My code:
struct node{
int data;
struct node *left;
struct node *right;
};
( struct node *) createNode(int num)
{
struct node *newNode;
newNode = (struct node *) malloc(sizeof(struct node));
newNode->data = num;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
change
( struct node *) createNode(int num)
to
struct node * createNode(int num)
Remember, you're specifying the return type. You're not typecasting.
That said,
Please see why not to cast the return value of malloc() and family in C.
Always check for the return value of malloc() for success before using the returned pointer.
Function: ( struct node *) createNode(int num) is invalid syntax. A pointer to a struct node* is the return type of the function. It seems you may have thought you must cast it to the struct type. That is not necessary. Furthermore, there is no need to cast malloc in C. Change it to this.
struct node* createNode(int num)
{
/* ... */
}
Not necessary, but, to save on typing struct each time, better yet, you can define a new type with typedef.
typedef struct node Node;
struct node{
int data;
Node *left;
Node *right;
};
While returning the structure you don't need to give the parenthesis for that. So simply You give the
struct node * createNode(int num){
...
}
Placing the brackets that is not correct.
You dont have to use parenthesis in return type of function definition. I think you are confused with the function definition here are few links:-
http://www.tutorialspoint.com/cprogramming/c_functions.htm
For function returning pointers
http://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm
Type casting can only be use to a constant, variable, function calls (if returning something).
Explicit type conversion rule:-
http://www.tutorialspoint.com/cprogramming/c_type_casting.htm
For example, I have a function:
void build()
{
struct Node *node;
node = (struct Node*)malloc(sizeof(struct Node));
}
Is it possible to access the pointer "node" from the outside?
C is a pretty straightforward and simple language. The only choice you have is to explicitlly put the node value somewhere, eiter:
global variable
parameters on the function
return value
Options 2 and 3 are the most common ones. As an argument to the function:
void build(struct Node **node_param)
{
struct Node *node;
node = (struct Node*)malloc(sizeof(struct Node));
*node_param = node;
}
For option 3 can be simply:
struct Node * build()
{
struct Node *node;
node = (struct Node*)malloc(sizeof(struct Node));
return node;
}
You can either create a standalone variable or create an struct with more fields in case you have many values to return from your function.
Is it possible to access the pointer "node" from the outside?
No, not this exact pointer since you don't know th memory address returned by malloc. You can access the Node instance pointed to by *node if you return initialized pointer out of the function or you pass it as an argument to this function, initialize inside the function and use after this.
example:
// pass pointer to pointer, so we will change original pointer not a copy
void build( struct Node **nodePtr)
{
struct Node *node;
node = malloc( sizeof( struct Node));
// ^^^^
// no need to cast result of malloc in C
*nodePtr = node;
// the rest...
}
I am trying to write a simple code to construct a tree in C language. Below is my code snippet.
#include<stdio.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
int main()
{
struct node *root = newNode(5);
//struct node *root = NULL; working piece
//newNode(&root,5); working piece
if(root == NULL)
{
printf("No root\n");
return 0;
}
//root->left = newNode(4);
//root->right = newNode(3);
//root->left->left = newNode(2);
//root->right->right = newNode(1);
return 0;
}
struct node* newNode(int data)
{
struct node *temp;
temp = (struct node*) malloc(sizeof(struct node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return(temp);
}
When I try to return the structure node address, the compiler gives me the error
"rightNode.c", line 29: identifier redeclared: newNode
current : function(int) returning pointer to struct node {int data, pointer to struct node {..} left, pointer to struct node {..} right}
previous: function() returning int : "rightNode.c", line 12
But when I comment this struct node* newNode(int data) and try to define a function that returns int by passing the address of the structure to the function like below, it does not shows me any error.
int newNode(struct node **root,int data)
{
printf("Inside New Node\n");
return 0;
}
As far I know, it is legal in C to return the address of the structure to the calling function.
It is something to do with the compiler.
I am using cc compiler in unix environment
type cc
cc is a tracked alias for /apps/pcfn/pkgs/studio10/SUNWspro/bin/cc
Below is the command I used to compile cc rightNode.c
Any help would be appreciated...
You need to declare a newNode prototype before you use it.
// somewhere after struct node definition and before first use
struct node* newNode(int);
You also need to include stdlib.h to get malloc.
Put this struct node* newNode(int data) above the code and include stdlib.h.
You need a function prototype if you are going to use a function before you declare it. Also malloc is defined in stdlib.h.
There is no function prototype visible when you call struct node *root = newNode(5); so the compiler gets confused.
When the compiler cannot find a function declaration, it assumes that such function exists, but returning int. Declare struct node* newNode(int data); before you call newNode(...) in main.
In older versions of C, you did not need to declare a function before using it. In older C, functions that are not declared are assumed to return int and accept an unspecified number of arguments. This is the reason you are getting the error, because the compiler assumes the newNode function returns int, rather than struct node *.
In modern C (C99 and newer), you can no longer do this. You must declare functions before they are used. Some compilers still allow the old behaviour and warn against it, but a strictly conforming C99 program cannot use a function without declaring it first.
In your case, you should put the following line of code before your main function. This tells the compiler about the newNode function and how it should be called:
struct node *newNode(int);