473,666 Members | 2,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(s truct 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 10137
In article <i8************ **@newsread4.ne ws.pas.earthlin k.net>,
Jim Showalter <ji***********@ hotmail.comwrot e:
>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(s truct 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.ne ws.pas.earthlin k.net>,
Jim Showalter <ji***********@ hotmail.comwrot e:
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.earthl ink.net>,
Jim Showalter <ji***********@ hotmail.comwrot e:
>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(struc t list_node *node, void (*free_data)(vo id *));
void list_fprint(FIL E *stream, struct list_node *node);
struct list_node *string_node(st ruct 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(&he ad, 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(&he ad, 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(&he ad, 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(std out, 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(struc t list_node *node, void (*free_data)(vo id *))
{
struct list_node *next_node;

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

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

struct list_node *string_node(st ruct 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(d ata) + 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.earthl ink.net>,
Jim Showalter <ji***********@ hotmail.comwrot e:
>>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
2314
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
4036
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
7402
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 example, the manner in which I update element 1 depends on several other (randomly numbered) elements in the array. So, I can't change an element until I've figured out how every element changes.
7
1645
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
1828
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 be able to copy the item in the cell of list control and paste it into any cell. this should also make proper changes to the linked list too.
1
3383
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 be able to copy the item in the cell of list control and paste it into any cell. this should also make proper changes to the linked list too.
35
2826
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 easier without much of overhead. Then why not reference ? Thanks /P
4
5112
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) using a linked list works. The interface for the classes: template<class T> class Node {
31
2700
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: $ ./Main terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct NULL not valid
0
8440
marktang
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...
0
8352
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,...
0
8863
Oralloy
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...
1
8549
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5661
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4192
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...
0
4358
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2765
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
2
1763
bsmnconsultancy
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...

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.