How to pass arrow pointer into function? - c

struct node {
int x;
struct node *next;
};
void allocateMemory(struct node *some_node) {
some_node = malloc(sizeof(struct node));
}
In another function:
struct node add(struct node *root, struct node *thisNode, int value)
I try to call this:
allocateMemory(thisNode->next);
I get a runtime error. It does nothing.
Yet when I do the same thing as allocateMemory() in the said function, i.e:
thisNode->next = malloc(sizeof(struct node));
It does what it is supposed to do.
What am I doing wrong?

Here in that code :
void allocateMemory(struct node *some_node) {
some_node = malloc(sizeof(struct node));
}
You can write :
void allocateMemory(struct node **some_node) {
*some_node = malloc(sizeof(struct node));
}
And while calling :
allocateMemory(&thisNode->next);

You need to paas pointer to pointer.
When you have pointer, then you can change value which is that pointer pointing to, and when you want to change the actual pointer then you need go one step deeper.
Also function add shouldn't return value but pointer?
struct node {
int x;
struct node *next;
};
void allocateMemory(struct node **some_node) {
*some_node = (struct node*)malloc(sizeof(struct node));
}
struct node* add(struct node *root, struct node *thisNode, int value) {
allocateMemory(&thisNode->next);
thisNode->x = value;
root->next = thisNode;
return thisNode;
}

Related

Can I use a CreatNode function to return a struct rather than its steps repeated in All other functions?

I want to make a CreatNode() function in C to be called by other functions. I am playing around with code trying to reach great readability and functionality. The professor has a CreatEmptyList() function but not a CreatNode().She is negligent and not the capable of the concepts and C lagnguage and didn't give me an answer.
I don't need this exploration and trying ideas that come to my mind to pass the course, but my aim is to become a Dev not to graduate.
This is the code of the Prof:
typedef struct nodetype
{
int info;
struct nodetype *next;
} node;
node *head;
void createemptylist(node *head)
{
head=NULL;
}
void insertatbeginning(node *head, int item)
{
node *newNode;
/* allocate memory for the new node and initialize the data in it*/
newNode= malloc(sizeof(node));
newNode->info=item;
/* assign the value of head to the “next” of newNode*/
newNode->next=head;
/* assign the address of newNode to head */
head=newNode;
}
void insertatend(node *head, int item)
{
node *newNode;
newNode=malloc(sizeof(node));
newNode->info=item;
newNode->next=NULL;
if(head==NULL)
head=newNode;
else
{
node *prev=head;
while(prev->next!=NULL)
prev=prev->next;
prev->next=newNode;
}
}
All are the snippets from the PDF she provided not exactly a compilable code.
This is the code I am working on and it keeps giving errors:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int info;
struct Node *Next;
}ListNode;
ListNode CreatNode(ListNode *Head){///These steps not to be repeated using this function
printf("\n=================\nEntered CreatNode Function");
ListNode *NewNode;
NewNode = malloc(sizeof(ListNode));
return *NewNode;
}
void CreatList(ListNode *Head){
printf("\n=================\nEntered CreatList Function");
Head = NULL;
}
void InserBeg(ListNode *Head, int item){
///CreatNode() steps here
NewNode=CreatNode(&Head);
NewNode->info = item; ///Inesrt value
NewNode->Next = Head;///Insert Adress inside Head to the Next point
Head = NewNode;
printf("\nFinished InsertBeg Function");
printf("\nValue inserted is: %d\n=================\n", NewNode->info);
}
void Append(ListNode *Head, int item){
///CreatNode() steps here
///NewNode=CreatNode(Head);
NewNode ->info = item;
NewNode ->Next = NULL;
if (Head==NULL){
Head=ListNode
}
else{
ListNode *Prev=Head;
while(while->Prev!=NULL){
Prev = Prev->Next;
}
Prev->Next=NewNode;
}
}
int main(){
ListNode *Head;
CreatList(&Head);
InserBeg(&Head, 8);
return 0;
}
errors:
C:\Users\User\Desktop\all\C\Single Linked List test.c|27|error: incompatible types when assigning to type 'ListNode * {aka struct Node *}' from type 'ListNode {aka struct Node}'|
Undeclared NewNode struct errors since it can't see it
Any help on coding my idea in different ways or make my code work?
The provided by the professor code is very bad.
For starters she uses a global variable head. As the variable is declared in the file scope then it is already initialized as a null pointer. So this function
void createemptylist(node *head)
{
head=NULL;
}
does not make a great sense. And moreover it does nothing with the original pointer head because it accepts its argument by value. That is it deals with a copy of the value of the original pointer.
By this reason other functions insertatbeginning and insertatend are wrong because they do not change the original pointer head that they accept by value.
void insertatbeginning(node *head, int item)
{
//...
head=newNode;
}
void insertatend(node *head, int item)
{
//...
head=newNode;
//...
}
They change a copy of the value of the original pointer.
The same problem is present in your functions.
As for the function CreatNode then as is it does not make a sense.
ListNode CreatNode(ListNode *Head){///These steps not to be repeated using this function
printf("\n=================\nEntered CreatNode Function");
ListNode *NewNode;
NewNode = malloc(sizeof(ListNode));
return *NewNode;
}
For starters the parameter head is not used within the function. You need to pass an integer argument to the function that will be used as an initializer for the data member info.
Instead of an object of the type ListNode you should return a pointer to the dynamically allocated object. Otherwise the function returns a copy of the dynamically allocated object and as a result the function will produce a memory leak.
Within the functions InserBeg and Append the name NewNode is undefined as for example
void InserBeg(ListNode *Head, int item){
///CreatNode() steps here
NewNode=CreatNode(&Head);
//...
And you are calling the functions passing expressions of incompatible pointer type ListNode ** instead of ListNode *.
CreatList(&Head);
InserBeg(&Head, 8);
Here is a demonstration program that shows how the function CreateNode and for example InsertBeg can be defined.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int info;
struct Node *next;
} ListNode;
ListNode * CreateNode( int info )
{
ListNode *new_node = malloc( sizeof( *new_node ) );
if ( new_node != NULL )
{
new_node->info = info;
new_node->next = NULL;
}
return new_node;
}
int InsertBeg( ListNode **head, int info )
{
ListNode *new_node = CreateNode( info );
int success = new_node != NULL;
if ( success )
{
new_node->next = *head;
*head = new_node;
}
return success;
}
int main( void )
{
ListNode *head = NULL;
if ( InsertBeg( &head, 10 ) )
{
puts( "New node is added." );
}
else
{
puts( "Error: not enough memory." );
}
}
The program output is
New node is added.

How to return pointer adress for structure variable

I was working on data structures and while I was writing some code, I needed to return the address of the pointer that was defined in the structure. So here's my code but when I compile and run it, it doesn't work and give an error message as " assignment makes pointer from integer without a cast ". How should I rewrite it?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node{
int x;
struct Node *next;
};
void main(){
int i;
struct Node *head;
head = (struct Node*) malloc(sizeof(struct Node));
head->next=NULL;
/*Ekle(5,head);
Ekle(10,head);
Ekle(15,head);
printf("Enter the value of 'ara' element");
scanf("%d",&i);
Print(head);
ArayaEkle(i,20,head);
Print(head);*/
head = siraliEkle(10,head);
head = siraliEkle(5,head);
Print(head);
}
void Print(struct Node *root){
while(root->next!=NULL){
root = root->next;
printf("%d\n",root->x);
}
}
struct Node *siraliEkle(int sayi, struct Node *root){
if(root==NULL){
root = (struct Node*) malloc(sizeof(struct Node));
root->x = sayi;
root->next = NULL;
return root;
}
else if(root->next==NULL){
if(root->x>sayi){
struct Node *temp = (struct Node*) malloc(sizeof(struct Node));
temp->x = sayi;
temp->next = root;
root = temp;
return root;
}
}
}
You must declare (or define) functions before using them.
Without declaration nor definition, types of function arguments are assumed to int and it will cause trouble when actual types are not int.
struct Node{
int x;
struct Node *next;
};
/* add these declarations */
void Print(struct Node *root);
struct Node *siraliEkle(int sayi, struct Node *root);
int main(){ /* also return type should be standard int */
Also don't forget to return something from siraliEkle even if root != NULL && (root->next != NULL || root->x <= sayi).
If you want to return the address for the struct pointer use the declaration
struct Node *siraliEkle(int sayi, struct Node *root);
As below and return:
return &root;

I can not pass by reference my node

I dont want create general *head node and I want to pass by reference and chance my data but although create new node for next node I cant reach my new node on main.
İf I look n1.next in main I see it is null.Why ?What is wrong ?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
void add(struct node** head,int data){
struct node * tmp = *head;
while(tmp != NULL){
tmp = tmp->next;
}
tmp = (struct node*) malloc(sizeof(struct node));
tmp->data= data;
tmp->next=NULL;
}
int main()
{
struct node n1;
n1.data=5;
n1.next=NULL;
add(&(n1.next),15);
printf("%d",n1.next->data);
return 0;
}
Instead of using a head pointer, are you trying to pass in the last next pointer in the list, and then update that to point to your new node? If so, add() should be
void add(struct node** head, int data) {
struct node* p = malloc(sizeof(*p));
p->data = data;
p->next = NULL;
*head = p;
}

Node pointer to current Node during mutile function call

I have declared a global pointer ptr and want that it should point to current node during different function call.
This is a sample code where I am creating a new node in fun1 and inserting in link list. In func2 I want to update the other members of newNode in linklist with a different value.
Currently I am traversing the link list to get the current Node or last Node which I dont want since during insertion of new Records already we have to traverse to reach to last Node thus storing the address of last Node.
But by doing the below I am not getting the proper values. Kindly someone suggest where I went wrong.
I am doing like this :
#include<stdio.h>
#include <stdlib.h>
struct Node
{
int data1;
int data2;
struct Node* next;
};
struct Node* head=NULL;
struct Node* ptr =NULL; /* Global pointer */
void insertNode(struct Node ** , struct Node* );
void fun1();
void fun2();
void fun1()
{
struct Node* ptr1 =NULL;
ptr1 = (struct Node*)malloc(sizeof(struct Node*));
ptr1->data1=1; /* intilaizing with some values */
insertNode(&head,ptr1);
}
void fun2()
{
/* Updating the current Node in the linklist with new value . */
ptr->data2=2;
}
void insertNode(struct Node ** head, struct Node* NewRec)
{
if(*head ==NULL )
{
NewRec->next = *head;
*head = NewRec;
ptr=*head;
}
else
{
/* Locate the node before the point of insertion */
struct Node* current=NULL;
current = *head;
while (current->next!=NULL )
{
current = current->next;
}
NewRec->next = current->next;
current->next = NewRec;
ptr=current->next;
}
}
int main ()
{
fun1();
fun2();
while(head!=NULL)
{
printf("%d", head->data1);
printf("%d",head->data2);
head=head->next;
}
return 0;
}
You made a classic mistake.
This is wrong:
ptr1 = (struct Node*)malloc(sizeof(struct Node*));
The allocated space here is sizeof(struct Node*) which is the size of a pointer (usually 4 or 8 bytes depending on the platform). But you need to allocate space for the whole struct Node structure, whose size is sizeof(struct Node).
So you simply need this:
ptr1 = (struct Node*)malloc(sizeof(struct Node));
BTW: in C you don't cast the return value of malloc so you actually should write this:
ptr1 = malloc(sizeof(struct Node));

Declaration and initialisation of pointers in C

I'm brushing up on the initialization and declaration of pointers in C.
I wrote a piece of code :
struct node
{
int data;
struct node* right=NULL;
struct node* left=NULL;
};
struct node* newNode(int data)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = data;
return temp;
}
which returned an error. The error is :
expected ';' at end of declaration list
struct node* right=NULL;
I then changed the code to :
struct node
{
int data;
struct node* right;
struct node* left;
right = NULL;
left = NULL;
};
struct node* newNode(int data)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = data;
return temp;
}
which returned the same error.
Finally,
I changed the code to :
struct node
{
int data;
struct node* right;
struct node* left;
};
struct node* newNode(int data)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = data;
temp->right=NULL;
temp->left=NULL;
return temp;
}
The above piece of code compiles without any errors. Why is this so ?
You cannot initialize a struct member inside a struct declaration. You have to do it outside, in your code. The struct declaration declares a type, not a variable that can be initialized.

Resources