473,378 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

how to copy strings into a linked list?

I'm trying to write code that gets fixed-length strings from the user
and then stores them in a linked list.

Here's the definition of my list node:

struct node {char str[19]; struct node* next; };

And here is my attempt at Push(), the function that adds new nodes
to the list:

void Push(struct node** head, char *str) {

struct node* newNode = malloc(sizeof(struct node));
newNode->str = *str;
newNode->next = *head;
*head = newNode;
}

It worked fine when testing with int's, but I don't know how to get the
strings copied to "newNode->str".
Aug 23 '06 #1
6 10099
In article <i8**************@newsread4.news.pas.earthlink.net >,
Jim Showalter <ji***********@hotmail.comwrote:
>I'm trying to write code that gets fixed-length strings from the user
and then stores them in a linked list.
>Here's the definition of my list node:
>struct node {char str[19]; struct node* next; };
>And here is my attempt at Push(), the function that adds new nodes
to the list:
>void Push(struct node** head, char *str) {
struct node* newNode = malloc(sizeof(struct node));
You should check the result of the malloc() -- if there was no
available memory then malloc() will return a NULL pointer.
newNode->str = *str;
newNode->next = *head;
*head = newNode;
}
>It worked fine when testing with int's, but I don't know how to get the
strings copied to "newNode->str".
strncpy( &newNode->str, str, sizeof(newNode->str) - 1 );
newNode->str[sizeof newNode->str - 1] = '\0';

But this code depends upon you really wanting strings -- which is
to say, null terminated character arrays. You said that you
have "fixed-length strings": does that mean that there are 18
used characters and the 19th is for the null, or does that mean
that there are 19 used characters and you will supply the null
when needed? The code as written assumes that the null needs
to be stored and protects itself in case the null was not present
in the first 18 characters of the input.
--
Programming is what happens while you're busy making other plans.
Aug 23 '06 #2
Walter Roberson wrote:
In article <i8**************@newsread4.news.pas.earthlink.net >,
Jim Showalter <ji***********@hotmail.comwrote:
You should check the result of the malloc() -- if there was no
available memory then malloc() will return a NULL pointer.
Thanks - I will when I get this function working.
>
strncpy( &newNode->str, str, sizeof(newNode->str) - 1 );
newNode->str[sizeof newNode->str - 1] = '\0';
I think you're close, but now I'm getting:
"warning: passing argument 1 of ‘strncpy’ from incompatible pointer type"
>
.... does that mean that there are 18
used characters and the 19th is for the null, ...
Yes

Aug 23 '06 #3
In article <29****************@newsread2.news.pas.earthlink.n et>,
Jim Showalter <ji***********@hotmail.comwrote:
>Walter Roberson wrote:
>.... does that mean that there are 18
used characters and the 19th is for the null, ...
>Yes
In that case, you can use strcpy() instead of strncpy(), and
you can skip the statement that sets the final character to '\0'.
However, it is -safer- to use strncpy() and set the '\0'
as that way a small mistake somewhere else in constructing the
string will not end up potentially trashing random bits of memory.
>strncpy( &newNode->str, str, sizeof(newNode->str) - 1 );
>I think you're close, but now I'm getting:
"warning: passing argument 1 of ‘strncpy’ from incompatible pointer type"
Ugly, why doesn't the warning message just stick to the basic
character set instead of moving into UTF-8 extensions for whatever
kind of quotation marks it is using around strncpy ?

Anyhow, better than &newNode->str would be either
newnode->str without the &, or else &newNode->str[0]

--
Programming is what happens while you're busy making other plans.
Aug 23 '06 #4
Jim Showalter wrote:
>
I'm trying to write code that gets fixed-length strings from the user
and then stores them in a linked list.
In line_to_string.c, string_node is the function
which copies strings into a linked list.

/* BEGIN line_to_string.c */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

struct list_node {
struct list_node *next;
void *data;
};

int line_to_string(FILE *fp, char **line, size_t *size);
void list_free(struct list_node *node, void (*free_data)(void *));
void list_fprint(FILE *stream, struct list_node *node);
struct list_node *string_node(struct list_node **head,
struct list_node *tail,
char *data);

int main(void)
{
struct list_node *head, *tail;
int rc;
char *buff_ptr;
size_t buff_size;
long unsigned line_count;

puts(
"\nThis program makes and prints a list of all the lines\n"
"of text entered from the standard input stream.\n"
"Just hit the Enter key to end,\n"
"or enter any line of characters to continue."
);
tail = head = NULL;
line_count = 0;
buff_size = 0;
buff_ptr = NULL;
while ((rc = line_to_string(stdin, &buff_ptr, &buff_size)) 1) {
++line_count;
tail = string_node(&head, tail, buff_ptr);
if (tail == NULL) {
break;
}
puts(
"\nJust hit the Enter key to end,\n"
"or enter any other line of characters to continue."
);
}
switch (rc) {
case EOF:
if (buff_ptr != NULL && strlen(buff_ptr) 0) {
puts("rc equals EOF\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&head, tail, buff_ptr);
}
break;
case 0:
puts("realloc returned a null pointer value");
if (buff_size 1) {
puts("rc equals 0\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&head, tail, buff_ptr);
}
break;
default:
break;
}
if (line_count != 0 && tail == NULL) {
puts("Node allocation failed.");
puts("The last line entered didnt't make it onto the list:");
puts(buff_ptr);
}
free(buff_ptr);
puts("\nThe line buffer has been freed.\n");
printf("%lu lines of text were entered.\n", line_count);
puts("They are:\n");
list_fprint(stdout, head);
list_free(head, free);
puts("\nThe list has been freed.\n");
return 0;
}

int line_to_string(FILE *fp, char **line, size_t *size)
{
int rc;
void *p;
size_t count;

count = 0;
while ((rc = getc(fp)) != EOF) {
++count;
if (count + 2 *size) {
p = realloc(*line, count + 2);
if (p == NULL) {
if (*size count) {
(*line)[count] = '\0';
(*line)[count - 1] = (char)rc;
} else {
ungetc(rc, fp);
}
count = 0;
break;
}
*line = p;
*size = count + 2;
}
if (rc == '\n') {
(*line)[count - 1] = '\0';
break;
}
(*line)[count - 1] = (char)rc;
}
if (rc != EOF) {
rc = count INT_MAX ? INT_MAX : count;
} else {
if (*size count) {
(*line)[count] = '\0';
}
}
return rc;
}

void list_free(struct list_node *node, void (*free_data)(void *))
{
struct list_node *next_node;

while (node != NULL) {
next_node = node -next;
free_data(node -data);
free(node);
node = next_node;
}
}

void list_fprint(FILE *stream, struct list_node *node)
{
while (node != NULL) {
fputs(node -data, stream);
putc('\n', stream);
node = node -next;
}
}

struct list_node *string_node(struct list_node **head,
struct list_node *tail,
char *data)
{
struct list_node *node;

node = malloc(sizeof *node);
if (node != NULL) {
node -next = NULL;
node -data = malloc(strlen(data) + 1);
if (node -data != NULL) {
if (*head == NULL) {
*head = node;
} else {
tail -next = node;
}
strcpy(node -data, data);
} else {
free(node);
node = NULL;
}
}
return node;
}

/* END line_to_string.c */
--
pete
Aug 24 '06 #5
Walter Roberson wrote:
In article <29****************@newsread2.news.pas.earthlink.n et>,
Jim Showalter <ji***********@hotmail.comwrote:
>>Walter Roberson wrote:

In that case, you can use strcpy() instead of strncpy(), and
you can skip the statement that sets the final character to '\0'.
However, it is -safer- to use strncpy() and set the '\0'
as that way a small mistake somewhere else in constructing the
string will not end up potentially trashing random bits of memory.
Thanks for the tip. I may stick with strncpy() as you suggest.
>
Anyhow, better than &newNode->str would be either
newnode->str without the &, or else &newNode->str[0]
newnode->str works. Thank you!

Aug 24 '06 #6
pete wrote:
>
In line_to_string.c, string_node is the function
which copies strings into a linked list.

/* BEGIN line_to_string.c */
Wow - thanks for the routines! And it all compiled without a whimper. That
should get me over this particular hurdle.
>
/* END line_to_string.c */
Thanks again, pete!
Aug 24 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Brent W. Hughes | last post by:
I kind of hate to have to convert a string into a list, manipulate it, and then convert it back into a string. Why not make strings mutable?
8
by: Chinmoy Mukherjee | last post by:
when the node structure is like struct node { node *next; node *rand; (// random is supposed to point to another node int value; }
7
by: simkn | last post by:
Hello, I'm writing a function that updates an array. That is, given an array, change each element. The trick is this: I can't change any elements until I've processed the entire array. For...
7
by: David. E. Goble | last post by:
Hi all; I need to build a list of strings in one function and use the list in another function. ie buildlist(char list, FILE **infile); { int i;
1
by: raniyesudas | last post by:
In our project we have to use pop up menu to cut,copy,paste items to linked list. the items of the list are displayed in the list control.Hence by clicking on the item in the list control we should...
1
by: raniyesudas | last post by:
In our project we have to use pop up menu to cut,copy,paste items to linked list. the items of the list are displayed in the list control.Hence by clicking on the item in the list control we should...
35
by: dragoncoder | last post by:
Just a simple theoritical question to the experts. What was the rationale behind making STL containers follow copy semantics rather than reference semantics. References almost always make things...
4
by: Beow | last post by:
Hello, I'm still very new to C++ and have encountered some trouble in understanding how exactly the copy constructor for a stack class (given as an example in the book I've been learning from)...
31
by: Markus Pitha | last post by:
Hello, I'm using a template to simulate a LinkedList from Java.It works without problems, but when I want to use strings in main.cpp instead of char*, I get the following error message: $...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.