Storing input from user into linked list using array - c

So I'm trying to get input from user and store it in linked list, using array (every 5 chars a new linked list is created). After getting EOF I want to print the input (actually print the arrays in each linked list)
here is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
typedef struct charNode {
int arr[MAX];
struct charNode *next;
} charNode;
void addNode();
void printAll();
int main(){
int c,i;
charNode *head=malloc(sizeof(charNode));
charNode *current=head;
while((c=getchar())!=EOF){
while(i<MAX){
current->arr[i++]=c;
}
i=0;
addNode(current);
}
printAll(head);
return 0;
}
void addNode(charNode *current){
struct charNode *link = (struct charNode*) malloc(sizeof(struct charNode));
current->next =link;
link->next = NULL;
current=current->next;
}
void printAll(charNode *head){
int j=0;
while(head->next!=NULL){
while(j<MAX){
printf("\n %d \t",head->arr[j++]);
}
printAll(head->next);
}
return;
}
and I'm getting "Segmentation fault (core dumped)" error..

This is Undefined behavior:
int c,i;
charNode *head=malloc(sizeof(charNode));
charNode *current=head;
while((c=getchar())!=EOF){
while(i<MAX){
current->arr[i++]=c;
}
since you are using i uninitialized to access your array, which could produce the Segmentation fault.
Change this:
printf("\n %d \t",head->arr[j++]);
to this:
printf("\n %c \t",head->arr[j++]);
so that you print characters, instead of numbers.
Simply initialize i to 0 for a start, happy debugging! =)

int main(){
char c;
charNode *head=malloc(sizeof(charNode));
charNode *current=head;
int i = 0;
while((c=getchar())!=EOF){
getchar();
while(i<MAX){
current->arr[i++]=c;
}
i=0;
addNode(&current);
}
printAll(head);
return 0;
}
void addNode(charNode **current){
struct charNode *link = malloc(sizeof(struct charNode));
link->next = NULL;
(*current)->next =link;
*current=(*current)->next;
}
void printAll(charNode *head){
int j=0;
if(head!=NULL){
while(j<MAX){
printf("%c\n",head->arr[j++]);
}
if(head->next != NULL)
printAll(head->next);
}
}
I changed your code a bit. Especially take a good look at addNode(). Now it works correctly

Related

The following program below works but a dialog box appears saying that the filename.exe has stopped working. Why so?

This program is supposed to be a demonstration for deleting a node from a linked list.
The program works and output is the same as desired but soon after a dialog box appears saying that the executable file has stopped working. I used code-blocks as the IDE and C-programming language. I would like to know why that happened and how to avoid it happening in the future. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
void create(struct node *first,int a[])
{
struct node *t,*last;
int i;
first->data=a[0];
first->next=NULL;
last=first;
for(i = 1; i < 5; i++)
{
t=(struct node *)malloc(sizeof(struct node));
t->data=a[i];
t->next=NULL;
last->next=t;
last=t;
}
}
void display(struct node *f)
{
int i;
for(i=0;i<5;i++)
{
printf("%d ",f->data);
f=f->next;
}
}
int delete(struct node * f,int pos)
{
int i,x;
struct node *q=NULL;
if (pos < 1 || pos > 5) {
return -1;
}
if (pos == 1) {
q=f;
f=f->next;
x=q->data;
free(q);
return x;
}
for (i = 0; i < pos - 1; i++)
{
q=f;
f=f->next;
}
q->next=f->next;
x=f->data;
free(f);
return x;
}
int main()
{
int a[]={3,5,7,8,9};
struct node *first;
int pos=4,t;
first=(struct node *)malloc(sizeof(struct node));
create(first,a);
t=delete(first,pos);
display(first);
return 0;
}
The issue is on display function where f is null
A solution is to remove the for loop and use a while testing if f is null or not.
I have also added a final \n to flush stdout
void display(struct node *f)
{
while (f)
{
printf("%d ",f->data);
f=f->next;
}
printf("\n");
}

Finding path between nodes using BFS in C language

I'm new to C language and it's been harder for me to work with pointers after working in JavašŸ˜„
I was trying to write a code of finding a path (not necessary minimum) between two nodes in a graph using breadth-first-search.
Here is my code :
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 200
void push(int a);
int pop(void);
void bfs(int a,int b,int len);
int nextnode(int a);
typedef struct node{
int data;
struct node* next;
}node;
int res[MAXSIZE];
int visited[MAXSIZE];
int rear,front;
node* graph[MAXSIZE];
int len;
int path[MAXSIZE];
int nextnode(int a)
{
if(graph[a]==NULL)
return -1;
else
{
struct node* c=graph[a];
while(visited[c->data]!=1 && c!=NULL)
{
c=c->next;
}
if(c==NULL)
return -1;
else
return c->data;
}
}
void push(int a)
{
path[rear]=a;
rear++;
}
int pop()
{
if(front==rear)
return -1;
int num=path[front];
front++;
return num;
}
int main()
{
rear=0;
len=0;
front=0;
int n,e;
int i,a,b;
printf("%s\n%s", "Inputting Graph... ","Enter number of nodes and edges: ");
scanf("%d %d",&n,&e);
printf("%s %d %s\n", "Graph Created with",n,"nodes without any edge.");
printf("%s\n","Enter the edges in 1 2 format if an edge exist from Node 1 to Node 2" );
for(i=1;i<=n;i++)
{
graph[i]=NULL;
visited[i]=0;
}
struct node* new = (struct node*)malloc(sizeof(struct node));
for(i=0;i<e;i++)
{
scanf("%d %d",&a,&b);
new->data=b;
new->next=NULL;
struct node* curr=graph[a];
if(curr==NULL)
{
graph[a]=new;
}
else
{
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=new;
}
}
printf("%s\n", "Graph Created Successfully.");
printf("%s", "Enter the node numbers between which the path is to be found between: ");
scanf("%d %d",&a,&b);
bfs(a,b,0);
printf("Length is %d\n",len);
for(i=1;i<=len;i++)
{
printf("%d\n",res[len]);
}
}
void bfs(int a,int b,int len)
{
int c;
visited[a]=1;
int flag=0;
while(a!=-1)
{
c=nextnode(a);
while(c!=-1)
{
c=nextnode(a);
if(c==b)
{
flag=1;
break;
}
push(c);
visited[c]=1;
}
len++;
res[len]=a;
if(flag==1)
{
res[len]=b;
break;
}
a=pop();
}
}
I know it's huge, but please mind going through it once. The problem I'm getting is Segmentation Fault after I input all the values, and before dfs() function call! Please Help.
For understanding: I have used array of Lists. Each array index denotes a node and the list denotes all the edges it is connected to. eg: if my Graph has 1->2, 1->3, 2-3 edges;
graph[1] will have a list 2->3->NULL. And graph[2] will have 3->NULL.
Thank you.
EDIT
As pointed out by Aditi, the error was in the line where nextnode function ran the while loop. After changing the code to
while(c != NULL && visited[c->data] == 1 )
the program ran flawlessly.
Thanks!
I think what you are trying to do is not graph[i] = NULL but graph[i]->next = NULL

Random graph with structures

I am trying to implement code for a random graph, where all vertices are connected to each other. The edges should be randomly selected. I wrote this code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define VOL 100
struct node{
int info;
struct node *next;
};
struct node *read_list(void){
struct node *p, *first=NULL;
int i,V;
for(i=0;i<V;i++){
p=malloc(sizeof(struct node));
p->next=first;
p->info=rand()%V;
first=p;
}
return(first);
}
void print_list(struct node *p){
while(p!=NULL){
printf("%d-> ", p->info);
p=p->next;
}
printf("NULL\n");
return;
}
int read_graph(struct node *G[]){
int i, V;
printf("Select a number of vertices:\n");
scanf("%d", &V);
for(i=0;i<V;i++){
printf("Adjacency list of vertex %d:\n", i);
G[i]=read_list();
}
return(V);
}
void print_graph(struct node *G[], int V){
int i;
printf("Adjacency lists of the graph:\n");
for(i=0;i<V;i++){
printf("Adjacency vertices to %d: ",i);
print_list(G[i]);
}
return;
}
int adj(int i, int j, struct node *G[]){
int r;
struct node *p;
p=G[i];
while (p!=NULL && p->info !=j)
p=p->next;
if(p==NULL)
r=1;
else
r=0;
return (r);
}
int main(){
srand(time(NULL));
struct node *G[VOL], *L;
int V;
V=read_graph(G);
print_graph(G, V);
L=read_list();
return 0;
}
However, it doesn't work and I don't know why. Xcode tells me 'build succeeded" but the code prints nothing (currently only 'Select a number of vertices'): no adjacency list, no edges.. Could you please check it and tell me where the errors are?
In the for statement below, the variable V is not initialized.
...
struct node *read_list(void) {
struct node *p, *first = NULL;
int i, V; // <<<<<<<<<<<<<<<<<<< V not initialized
for (i = 0; i<V; i++) {
//^ trouble here
...

Queue of Strings in C

I am trying to edit this program. Right now the users enters symbols and I want to make it work with Strings.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data;
struct Node *next;
};
struct queue
{
struct Node *top;
struct Node *bottom;
}*q;
void Write(char x)
{
struct Node *ptr=malloc(sizeof(struct Node));
ptr->data=x;
ptr->next=NULL;
if (q->top==NULL && q->bottom==NULL)
{
q->top=q->bottom=ptr;
}
else
{
q->top->next=ptr;
q->top=ptr;
}
}
char Read ()
{
if(q->bottom==NULL)
{
printf("Empty QUEUE!");
return 0;
}
struct Node *ptr=malloc(sizeof(struct Node));
ptr=q->bottom;
if(q->top==q->bottom)
{
q->top=NULL;
}
q->bottom=q->bottom->next;
char x=ptr->data;
free(ptr);
return x;
}
int main()
{
q= malloc(sizeof(struct queue));
q->top=q->bottom=NULL;
char ch='a';
printf("NOTE: To stop the entry, please enter 'q'!\n\n Enter a String: \n");
while(ch!='q')
{
scanf("%c",&ch);
Write(ch);
}
printf("\nThe entered String:\n\n");
while(q->bottom!=NULL)
{
ch=Read();
printf("%c",ch);
}
printf("\n\n");
system("PAUSE");
return 0;
}
So I am editing it like this (the code below) and I get error "[Error] incompatible types when assigning to type 'char[10]' from type 'char *'"
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data[10];
struct Node *next;
};
struct queue
{
struct Node *top;
struct Node *bottom;
}*q;
void Write(char x[10])
{
struct Node *ptr=malloc(sizeof(struct Node));
ptr->data=x;
ptr->next=NULL;
if (q->top==NULL && q->bottom==NULL)
{
q->top=q->bottom=ptr;
}
else
{
q->top->next=ptr;
q->top=ptr;
}
}
char Read ()
{
if(q->bottom==NULL)
{
printf("Empty QUEUE!");
return 0;
}
struct Node *ptr=malloc(sizeof(struct Node));
ptr=q->bottom;
if(q->top==q->bottom)
{
q->top=NULL;
}
q->bottom=q->bottom->next;
char x=ptr->data;
free(ptr);
return x;
}
int main()
{
q= malloc(sizeof(struct queue));
q->top=q->bottom=NULL;
char ch][10]='a';
printf("NOTE: To stop the entry, please enter 'q'!\n\n Enter a String: \n");
while(ch!='q')
{
scanf("%c",&ch);
Write(ch);
}
printf("\nThe entered String:\n\n");
while(q->bottom!=NULL)
{
ch=Read();
printf("%c",ch);
}
printf("\n\n");
system("PAUSE");
return 0;
}
I can't solve this problem, so I would love to get some help...
You can't assign to an array, but you can copy to it.
To copy a string use strcpy:
strcpy(ptr->data, x);
Or since you have a limited array, maybe use strncpy:
strncpy(ptr->data, x, sizeof(ptr->data) - 1);
ptr->data[sizeof(ptr->data) - 1] = '\0';
For strncpy it will not add the terminating '\0' character if the source is equal or longer than the specified length, so we have to make sure that the string is properly terminated.

storing an array as a linked list in C

I'm working in C and am having some trouble. I need to store an array of chars (string) across a linked list. In other words, convert a string to a linked list. Basically, one character per node. For example string, dog\0, rather then storing a null character in the last node it would just point to a null pointer to signify the end of the stringā€¦ā€¦ d->o->g->NULL
An suggestions would be great, thank you
int main(){
char *string;
string = malloc(sizeof(char)*100);
strcpy(string,"cheese");
node *list = NULL;
list = createNode(string[0]);
int i;
for(i=1;i<strlen(string);i++){
// this is where I'm stuck, the first char 'c'is in,
// I'm guessing i wanna loop through and
// store each char in a new node ?
}
return 0;
}
node *createNode(char data){
node *ptr = malloc(sizeof(node));
if (ptr == NULL)
{
return NULL;
}
ptr->data = data;
ptr->next = NULL;
return ptr;
}
Here is how to do this in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
node *next;
char data;
};
node *createNode(char data, node *parent) {
node *ptr=(node*)malloc(sizeof(node));
if(ptr==NULL) {
fprintf(stderr, "Memory allocation error.\n");
exit(1);
}
if(parent!=NULL) parent->next=ptr;
ptr->data=data;
ptr->next=NULL;
return ptr;
}
int main() {
char str[]="cheese";
// Store the string to the list
node *first=NULL, *cur=NULL;
for(int i=0, len=strlen(str); i<len; i++) {
cur=createNode(str[i],cur);
if(first==NULL) first=cur;
}
// Now print it out
cur=first;
while(cur!=NULL) {
printf("%c\n", cur->data);
cur=cur->next;
}
_getwch();
return 0;
}
If C++ is OK then here is a working sample:
#include <iostream>
#include <list>
using namespace std;
int main() {
char str[]="cheese", chr;
// Store the string in the list
std::list<char> clist;
for (int i=0, len=strlen(str); i<len; i++)
clist.push_back(str[i]);
clist.push_back('\0');
// Display the list
do {
chr=clist.front();
cout<<chr<<endl;
clist.pop_front();
} while(chr);
_getwch();
return 0;
}

Resources