Hi All,
As a beginner in Computer Programming, I decided to create Linked List using recursion, but I am not getting right answer. I think it is fundamentally correct, but I am stuck.
Please help me, - #include "stdio.h"
-
-
struct node
-
{
-
int n;
-
struct node* link;
-
};
-
-
struct node* node1=NULL;
-
struct node* node2=NULL;
-
-
void create();
-
-
main()
-
{
-
char c;
-
printf("Do you want to create a linked list? ");
-
scanf("%c",&c);
-
if(c=='y')
-
create();
-
//Displaying Elements of the Linked List
-
while(node2!=NULL)
-
{
-
printf("%d",node2->n);
-
node2=node2->link;
-
}
-
}
-
-
-
void create()
-
{
-
struct node a;
-
char ch;
-
if(node1==NULL)
-
{
-
printf("\nEnter the Integer Value: ");
-
scanf("%d",&(a.n));
-
a.link=NULL;
-
node1=&a;
-
node2=&a;
-
}
-
else
-
{
-
printf("\nEnter the Integer Value: ");
-
scanf("%d",&(a.n));
-
a.link=NULL;
-
node1->link=&a;
-
node1=node->link;
-
}
-
printf("\nDo you want to enter more elements in linked list? ");
-
scanf("%s",&ch);
-
if(ch=='n')
-
return;
-
else
-
create();
-
}
Thanx
Suyash.Upadhyay
6 8656 horace1 1,510
Recognized Expert Top Contributor
in create() -
void create()
-
{
-
struct node a;
-
a is a local variable which is lost on function exit.
make a a pointer and use malloc() to allocate storage, e.g. -
void create()
-
{
-
struct node *a=malloc(sizeof(struct node));
-
char ch;
-
if(node1==NULL)
-
{
-
printf("\nEnter the Integer Value: ");
-
scanf("%d",&(a->n));
-
a->link=NULL;
-
node1=a;
-
node2=a;
-
}
-
... etc etc
-
Thanx,
I got right Output, but can you please clarify one doubt:-
Structure is user defined data type, so when we instatiate it some space in memory should be get allocated for that variable( just like when we declare int a; some space allocates for a), then why should we explicitly use malloc function.
Please help me,
Suyash.Upadhyay
Thanx,
I got right Output, but can you please clarify one doubt:-
Structure is user defined data type, so when we instatiate it some space in memory should be get allocated for that variable( just like when we declare int a; some space allocates for a), then why should we explicitly use malloc function.
Please help me,
Suyash.Upadhyay
there are four scopes in c, in general
block, function, file and program scope. some people refer global scope as program scope.
At the end of scope usually the variable space or memory occupied by variable is freed and returned to operating system. (for this reason usually these variables are stored in stack)
Memory allocated by malloc are from heap and this persist between function calls(unless you free them using free()).
there are four scopes in c, in general
block, function, file and program scope. some people refer global scope as program scope.
At the end of scope usually the variable space or memory occupied by variable is freed and returned to operating system. (for this reason usually these variables are stored in stack)
Memory allocated by malloc are from heap and this persist between function calls(unless you free them using free()).
Thanx but I have still a problem.
In my program node2 is defined in program scope.I have printed node->n immediately after assignment of node2=&a ( where a is an instance of structure)
it gives right result, but when I tried to print node2->n just outside that block it always gives result as 0. What's the problem with it. Please have a glance at my code. - #include "stdio.h"
-
-
struct node
-
{
-
int n;
-
struct node* link;
-
};
-
-
struct node* node1=NULL;
-
struct node* node2=NULL;
-
struct node* node3;
-
-
void create();
-
-
main()
-
{
-
char c;
-
printf("Do you want to create a linked list? ");
-
scanf("%c",&c);
-
if(c=='y')
-
create();
-
}
-
-
-
void create()
-
{
-
struct node a;
-
char ch;
-
if(node1==NULL)
-
{
-
printf("\nEnter the Integer Value: ");
-
scanf("%d",&(a.n));
-
a.link=NULL;
-
node1=&a;
-
node2=&a;
-
printf("\nTesting1 %d",node2->n);
-
}
-
else
-
{
-
printf("\nEnter the Integer Value: ");
-
scanf("%d",&(a.n));
-
a.link=NULL;
-
node1->link=&a;
-
node1=node1->link;
-
printf("\nTesting2 %d",node1->n);
-
}
-
printf("\nDo you want to enter more elements in linked list? ");
-
scanf("%s",&ch);
-
printf("\nTesting2.5 %d",node2->n); //it gives output 0
-
if(ch=='n')
-
return;
-
else
-
{
-
printf("\nTesting3 %d",node2->n);
-
while(node3!=NULL)
-
{
-
printf("\nTesting4 %d",node2->n); // always prints 0
-
printf("\n");
-
node3=node3->link;
-
}
-
create();
-
}
-
}
Please help me.
Suyash.Upadhyay
horace1 1,510
Recognized Expert Top Contributor
in the following you read ch which is a char using conversion specification %s which is for a string -
printf("\nDo you want to enter more elements in linked list? ");
-
scanf("%s",&ch);
-
and you are corrupting memory
change the conversion specification to %c to read a char -
printf("\nDo you want to enter more elements in linked list? ");
-
getchar(); // read last newline
-
scanf("%c",&ch);
-
printf("\nTesting2.5 %d",node2->n); //it gives output 0
-
you need the getchar() to remove the newline entered after the last integer value
Ganon11 3,652
Recognized Expert Specialist
In my program node2 is defined in program scope.I have printed node->n immediately after assignment of node2=&a ( where a is an instance of structure)
it gives right result, but when I tried to print node2->n just outside that block it always gives result as 0. What's the problem with it.
In the function, you have created a node a with function scope. Then you have node2 point to this temporary node - during the function, node2 is properly defined and will act as planned. But as soon as the function exits, the node created by a is de-allocated. Suddenly, node2 points to de-allocated (a.k.a. useless) memory.
If you are using C++, you should create a node object for node2 using the new operator. If you are using C, you should create a node object using malloc.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: M. Katz |
last post by:
I'm trying to create a heirarchical linked list of sorts, and I'm
looking for advice as to how best to set up the arrays. In other
languages, I might use a pointer array to other pointer arrays, but in
PHP, I'm a bit stumped.
What I have is a list of simple, small arrays. I'd like to figure out
the appropriate data structure so that each element knows which
element is it's "parent," and so that each element can have multiple
children....
|
by: Jeffrey Silverman |
last post by:
Hi, all. I have a linked list. I need an algorithm to create a tree
structure from that list.
Basically, I want to turn this:
$list = array(
array( 'id' => 'A', 'parent_id' => null, 'value' => 'aaa')
, array( 'id' => 'B', 'parent_id' => 'A', 'value' => 'bbb')
, array( 'id' => 'C', 'parent_id' => 'B', 'value' => 'ccc')
, array( 'id' => 'D', 'parent_id' => 'A', 'value' => 'ddd')
|
by: junky_fellow |
last post by:
Consider a singly-linked list. Each node has a structure,
struct node {
char c;
struct node *next;
};
Each of the nodes contain an alphabetic character.
Can anybody suggest a way to print the characters in reverse order.
|
by: dssuresh6 |
last post by:
Whether browsing forward or backward can be done using a singly linked
list. Is there any specific case where a doubly linked list is needed?
For people who say that singly linked list allows traversal only in one
direction, I would say that using appropriate loops/recursion, traversal
in opposite direction is also possible. Then why the need for doubly
linked list?
--
|
by: alternativa |
last post by:
Hello,
I'm a beginner in C programming and I have a problem that probably will
seem trivial to most of you, however I can't find a solution...
So, I have to write a data base - program should ask the user about the
data and then do some operations like sorting etc. I decided to use a
linked list. The code looks as follows:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
| |
by: joshc |
last post by:
In an interview for an embedded software position recently I was asked
to write code, in C, for printing the contents of a linked list
backwards. After a few minutes I came up with the recursive solution.
Being that recursion is frowned upon in embedded software, the answer
was not what the interviewer expected, but alas it was correct. I asked
some friends how they would have answered and another answer is to
reverse the list and then...
|
by: tgnelson85 |
last post by:
Hello, C question here (running on Linux, though there should be no platform specific code).
After reading through a few examples, and following one in a book, for linked lists i thought i would try my own small program. The problem is, I seem to be having trouble with memory, i.e. sometimes my program will work and display the correct output, and sometimes it will not and display garbage (in a printf call) so i assume i have been using...
|
by: DanielJohnson |
last post by:
Hi,
I am not seeking a solution nor am I asking a homework problem. I have
my solution but it doesn't run correctly as expected because of some
error and I am trying to understand this error. Here is my code
node* Reverse_List(node *p)
{
/*Is there any problem with this statement */
static node *head = p;
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |