this is the code for printing the two strings together but whenever I try to run it, there's a segmentation error but it compiles without any error, can anyone help?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char *data; //string data in this node
struct node *next; //next node or NULL if none
} Node;
void print(Node *head); //function prototype print
Node *push_node(Node x, Node *strlist);
int main ()
{
Node node1;
Node node2;
Node *list = NULL;
strcpy(node1.data, "world");
push_node(node1, list);
strcpy(node2.data, "hello");
push_node(node2, list);
print(list);
return 0;
}
void print(Node *head)
{
Node *p = head;
while (p != NULL)
{
printf("%s", p->data);
p = p->next;
}
}
Node *push_node(Node x, Node *strlist)
{
x.next= strlist;
return &x;
}
You declared two objects of the type Node
Node node1;
Node node2;
data members of which are not initialized. That is the pointers data of the objects have indeterminate values.
So calling the function strcpy
strcpy(node1.data, "world");
strcpy(node2.data, "hello");
results in undefined behavior.
Also the pointer list is not being changed within the program. It is always equal to NULL as it was initialized. So calling the function print does not make a sense.
To make your code at least working you need to make the following changes.
Node *push_node(Node *x, Node *strlist);
//...
node1.data = "world";
list = push_node( &node1, list);
node2.data = "hello";
list = push_node( &node2, list);
print(list);
//...
Node *push_node(Node *x, Node *strlist)
{
x->next= strlist;
return x;
}
Related
I had a singly linked list that took in integers successfully, but now I want to use strings. However it is not working. I am getting so many different errors about "casting". I am finding conflicting information online as well. One comment here, Creating linked list of strings, said not to use strcpy, but I see strcpy used in a few examples online.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
struct node {
char value[];
struct node* next; // pointer of structure type
};
// set existing type, node, to the alias, node_t
typedef struct node node_t;
node_t *create_new_node(char value) {
// create space for node with malloc
node_t *result = malloc(sizeof(node_t));
// set the value of the new node
result->value = value;
//strcpy(result->value, value);
// set the value's next pointer to null
result->next = NULL;
return result;
}
node_t *insert_at_head(node_t **head, node_t *node_to_insert) {
node_to_insert->next = *head;
*head = node_to_insert;
return node_to_insert;
}
//Prints linked list
void printlist(node_t* head) {
node_t *temporary = head;
while (temporary != NULL) {
//print out the value of the node that temporary points to
// printf("%d - ", temporary->value);
// to move along the list
temporary = temporary->next;
}
printf("\n");
}
int main() {
node_t *tmp;
// declaring head pointer
node_t *head = NULL;
// CREATING LINKED LIST
// for (int i = 0; i < 25; i++) {
// tmp = create_new_node(i);
// // sending the address of the head variable
// //calling by reference
// //SINCE HEAD IS ALREADY A NODE POINTER
// insert_at_head(&head, tmp);
// }
printlist(head);
tmp = create_new_node("I like food");
insert_at_head(&head, tmp);
}
How can I get this Linked List of string to work?
Thank you.
If you reorganize it a bit, you will be able to allocate the space the struct & the place for the string in the single malloc.
struct node
{
struct node* next; // pointer of structure type
char value[];
};
// set existing type, node, to the alias, node_t
typedef struct node node_t;
node_t *create_new_node(const char *value)
{
// create space for node with malloc
node_t *result = malloc(sizeof(*result) + strlen(value) + 1);
if(result)
{
strcpy(result->value, value);
result->next = NULL;
}
return result;
}
Please use your compiler! I ran $gcc -Wall a.c on this code and got:
a.c:7:10: error: flexible array member not at end of struct
char value[];
^
a.c: In function ‘main’:
a.c:67:5: warning: passing argument 1 of ‘create_new_node’ makes integer from pointer without a cast [enabled by default]
tmp = create_new_node("I like food");
^
a.c:15:9: note: expected ‘char’ but argument is of type ‘char *’
node_t *create_new_node(char value) {
^
a.c:70:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
Now we know what the problems are. Firstly, char value[] should be char *value since it's a pointer rather than a flexible array member (FAM). You could also move the FAM to the end of the struct if you want as shown here.
Next, node_t *create_new_node(char value) is relying on a char value when you really want a string, char *value for the parameter. There are issues beyond this: you'll likely want to make a copy of the string for the node in case it disappears from the stack. This memory should be cleaned up after use.
Other tips:
Avoid noisy, redundant comments like:
// declaring head pointer
node_t *head = NULL;
malloc(sizeof(*name_of_the_var)); is safer than malloc(sizeof(node_t)); if the data changes.
node_t *insert_at_head(node_t **head, node_t *node_to_insert) modifying its parameter and returning it is a little unusual. I'd make it void to make the in-place contract explicit.
Alphabetize and remove unused imports.
Check that malloc calls succeeded.
Remember to return 0; from main.
typedef struct node node_t; is okay but also hides info--I prefer keeping the struct there.
Here's a possible rewrite:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char *value;
struct node* next;
};
struct node *create_new_node(char *value) {
struct node *node = malloc(sizeof(*node));
if (!node) {
fprintf(stderr, "%s:%d malloc failed\n", __FILE__, __LINE__);
exit(1);
}
node->next = NULL;
node->value = strdup(value);
if (!node->value) {
fprintf(stderr, "%s:%d malloc failed\n", __FILE__, __LINE__);
exit(1);
}
return node;
}
void insert_at_head(struct node **head, struct node *node_to_insert) {
node_to_insert->next = *head;
*head = node_to_insert;
}
void print_list(struct node *head) {
for (; head; head = head->next) {
printf("%s->", head->value);
}
puts("");
}
void free_list(struct node *head) {
while (head) {
struct node *tmp = head;
head = head->next;
free(tmp->value);
free(tmp);
}
}
int main() {
struct node *head = NULL;
for (int i = 0; i < 10; i++) {
char n[16];
sprintf(n, "%d", i);
insert_at_head(&head, create_new_node(n));
}
print_list(head);
free_list(head);
return 0;
}
Output:
9->8->7->6->5->4->3->2->1->0->
This program should delete the N-node in a singly linked list. If i put N = 1 or N = 2 it's ok, the program works. But with N = 0 the output prints infinite nodes with random values (after deleting the node 0). I think the program can't see the new head. Thx for the help!
#include <stdio.h>
#include <stdlib.h>
#define N 0
struct node {
int data;
struct node *next;
};
void printlist(struct node *head){
struct node *current=head;
int i=0;
while (current!=NULL){
printf("node number %d \t : %d\n", i, current->data);
current=current->next;
i++;
}
}
int deletenode(struct node *head,int n){
struct node *current=head;
struct node *previous=head;
int i=0;
while(current!= NULL){
if (n==i && i!=0){
previous->next=current->next;
free(current);
return 1;
}
else if (n==i && i==0){
head=head->next;
free(current);
return 1;
}
i++;
previous=current;
current=current->next;
return 0;
}
printf("error\n");
exit(EXIT_FAILURE);
}
void main(){
struct node *n1=malloc(sizeof(struct node));
struct node *n2=malloc(sizeof(struct node));
struct node *n3=malloc(sizeof(struct node));
struct node *head=n1;
n1->data=5;
n1->next=n2;
n2->data=10;
n2->next=n3;
n3->data=15;
n3->next=NULL;
printf("\n\nbefore\n");
printlist(head);
deletenode(head,N);
printf("\n\nafter\n");
printlist(head);
}
I'm using currentas a temp pointer , because after the head shift on the second node i need a pointer to the old head and use free.
C always passes by value, so changing a parameter has no effect on the caller.
void foo(int i) {
i = 1234; // No effect on caller.
}
void foo(int *p) {
p = NULL; // No effect on caller.
}
If you want to modify a variable (such as the caller's head), you need to pass a pointer to it. (You can still change that to which a pointer references.)
int deletenode(struct node **head, int n) {
...
}
deletenode(&head, N);
Now, you could simply replace every instance of head in your code with (*head) to account for the new calling convention, but that would waste an opportunity for simplification. By having a pointer to a struct node *, we don't need to handle head (a struct node *) and prev_node->next (a struct node *) differently.
int delete_node_n(struct node **ptr, unsigned n) {
// Make `ptr` point to the pointer we want to modify.
// This will either be the `head` variable
// or the `next` field of some node.
while (1) {
if (!*ptr)
return 0;
if (!n)
break;
ptr = &( (*ptr)->next );
--n;
}
struct node *to_free = *ptr;
*ptr = (*ptr)->next;
free(to_free);
return 1;
}
this code supposed to print : 'tree two one'
but it doesn't work. (the new_nod isn't added to the front of mylist)
anybody knows why? (actually in this code i wanted to use a function with a pointer to pointer input in another function but it didn't work(no changes applied to the mylist).
but it works when i'm using add_front function straightly in main.
#include <stdio.h>
#include <stdlib.h>
struct node{
char *word;
struct node *next;
};
struct node* create_node(char *str){
struct node *s;
s = (struct node *)malloc(sizeof(struct node));
if(s==NULL){
printf("couldn't malloc :(\n");
exit(-1);
}
s->word = str;
s->next = NULL;
return s;
}
void print_node(struct node *list){
struct node *current;
for(current = list; current !=NULL; current = current->next)
printf("%s ", current->word);
}
void add_front(struct node **list, struct node *new_node){
new_node->next= *list;
*list = new_node;}
void func(struct node*list, struct node*new_node){
add_front(&list, new_node);
}
int main()
{
struct node* mylist = create_node("one");
mylist->next = create_node("two");
struct node *new_node = create_node("tree");
func(mylist, new_node);
print_node(mylist);
}
Your add_front accepts a pointer to a pointer and other than missing a check for NULL is pretty much okay. But let's take a look at this:
void func(struct node*list, struct node*new_node){
add_front(&list, new_node);
}
What is add_front modifying here? The local pointer list. Which is just a copy of mylist in main.
So you haven't changed what mylist is pointing to.
I am trying to create a linked list of strings in C and have had problems adding the first Node into the list. For whatever reason my program prints NULL even though I reference the head variable to newNode but it does not copy the string from struct pointer to struct pointer. Any help is appreciated. Thanks!
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
typedef struct stringData {
char *s;
struct stringData *next;
} Node;
Node *createNode(char *s) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->s = s;
newNode->next = NULL;
return newNode;
}
void insert(Node *head, Node *newNode) {
if (head == NULL) {
head->s = newNode->s;
head = newNode;
}
}
void printList(Node *head) {
while (head != NULL) {
printf("%s\n", head->s);
head = head->next;
}
}
int main()
{
Node *head = createNode(NULL);
Node *a = createNode("A");
insert(head, a);
printList(head);
return 0;
}
Following code snippet is wrong:
void insert(Node *head, Node *newNode) {...}
...
insert(head, a);
You need to pass the pointer by reference. Currently you are changing local copy (argument).
Fix
Change your insert as:
void insert(Node **head, Node *newNode) {...}
And call as:
insert(&head, a);
What elseAtleast insert (and possibly) more functions are not fool-proof (guaranteed null pointer dereference, else case not handled etc). You need to debug and fix many such cases. Working your approach properly on paper before coding may help.
Here is a modified version of the code that gives an example of inserting new nodes at both the start of a list and the end of a list. In fact, the insert function could be used to insert a new node at any position in the list, since all it needs is a pointer to a link and a pointer to the node to be inserted.
#include <stdlib.h>
#include <stdio.h>
typedef struct stringData {
char *s;
struct stringData *next;
} Node;
Node *createNode(char *s) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->s = s;
newNode->next = NULL;
return newNode;
}
void insert(Node **link, Node *newNode) {
newNode->next = *link;
*link = newNode;
}
void printList(Node *head) {
while (head != NULL) {
printf("%s\n", head->s);
head = head->next;
}
}
int main(void)
{
Node *head = NULL;
Node *tail = NULL;
Node *n;
n = createNode("B");
// First node at start of list - head is updated.
insert(&head, n);
// First node is also the tail.
tail = n;
n = createNode("A");
// Insert node at start of list - head is updated.
insert(&head, n);
n = createNode("C");
// Insert node at end of list.
insert(&tail->next, n);
// Update tail.
tail = n;
printList(head);
return 0;
}
#include <stdio.h>
struct list
{
int data;
struct list *next;
};
struct list *start, *end;
void add(struct list *head, struct list *list, int data);
void delete(struct list *head, struct list *tail);
int main(void)
{
start=end=NULL;
add(start, end, NULL);
add(start, end, NULL);
printf("First element: %d");
delete(start, end);
return 0;
}
void add(struct list *head, struct list *tail, int data)
{
if(tail==NULL)
{
head=tail=malloc(sizeof(struct list));
head->data=data; head->next=NULL;
} else {
tail->next=malloc(sizeof(struct list));
tail=tail->next;
tail->data=data;
tail->next=NULL;
}
}
void delete(struct list *head, struct list *tail)
{
struct list *temp;
if(head==tail)
{
free(head);
head=tail=NULL;
} else {
temp=head->next;
free(head);
head=temp;
}
}
I am aiming to return an output of 3 but keep getting random results. Any insight is greatly appreciated
As you want to modify head and tail you need to pass a pointer to them.
i.e.
void add(struct list **head, struct list **tail, int data)
{
if(*tail==NULL)
{
*head = *tail = malloc(sizeof(struct list));
(*head)->data = data;
(*head)->next = NULL;
} else {
(*tail)->next = malloc(sizeof(struct list));
*tail = (*tail)->next;
(*tail)->data = data;
(*tail)->next = NULL;
}
}
Do similarly for the other function. Then head and tail will also change outside the function.
The line
printf("First element: %d");
It requires an integer to print - supply it - see the manual page for printf
Avoid using keywords for C++ in C programs - such as delete
Parameters of C functions are passed by value. Thus, the changes that you make to the values of head and tail in the add() function will not be reflected in main() from which add() is called.
And, it doesn't seem that you've supplied a second parameter for printf(), so the %d format is not going to get the integer value that it will be looking for.
In your program start and end are global variables, so there is no need to pass it as arguments to other functions, because other methods can directly access it.
//Structure to store data
struct list
{
int data;
struct list *next;
};
// global variables
struct list *start, *end;
void add(int);
void delete();
// start of program
int main(void)
{
start=end=NULL;
add(5);
add(6);
printf("\nFirst element: %d",start->data);
delete();
printf("\nFirst element: %d",start->data);
return 0;
}
//add node to list
void add(int data)
{
if(end==NULL)
{
start=end=malloc(sizeof(struct list));
start->data=data; start->next=NULL;
} else {
end->next=malloc(sizeof(struct list));
end=end->next;
end->data=data;
end->next=NULL;
}
}
// delete node from list
void delete()
{
struct list *temp;
if(start==end)
{
free(start);
start=end=NULL;
} else {
temp=start->next;
free(start);
start=temp;
}
}
OUTPUT:
First element: 5
First element: 6
Note:
If you don't want your start and end to be global than it can be a local variable of main function. Here you have to either work on double pointer mechanism or return memory address to retain the modification.
There are a number of problems here.
First, when you pass a pointer to a function, the pointer is passed by value. Any changes to the pointer in the called function will not be reflected in the calling function. To change what the pointer in the calling function is pointing to, you need to pass a pointer-to-pointer. So your add()function needs to be:
void add(struct list **head, struct list **tail, int data) {
if(*tail == NULL) {
*head = *tail = malloc(sizeof(struct list));
(*head)->data = data;
(*head)->next = NULL;
}
else {
(*tail)->next = malloc(sizeof(struct list));
(*tail) = (*tail)->next;
(*tail)->data = data;
(*tail)->next = NULL;
}
return;
}
And your delete() function needs to be changed similarly.
Secondly, you are passing NULL as your data value to the add function. NULL is a pointer; it is typically defined as a macro, and could be (void*) 0 in the implementation. It should not be used as an integer. Pass 0 as the integer, not NULL.
Third, you have this statement:
printf("First element: %d");
Your format string has the conversion specifier %d but there is no argument that matches the %d. This is undefined behavior. What integer exactly are you trying to print?
Where do you expect the output 3, and for what reason?