PDA

View Full Version : C structs


master terrence
September 19th, 2008, 02:24 PM
I'm at a loss for ideas here.

I had a struct with one int and a pointer (link list) and got that to print easily.
Now I have added a string to it... it won't print at all. (this is my first linked list with a string btw :/ )

here's the code:
//whenever it enters the print function it freezes :(

/*
To create a linked list by adding elements at the rear, and to print the list
*/
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
char fun;
struct node *next;
};
struct node* Addrear(struct node *list, int d, char f) ;
void PrintList( struct node *list);
main( ) {
int number = 0;
char f;
struct node *pList=NULL;
while(number!= -1)
{
printf("enter data for next node \n ");
scanf("%d", &number);
if(number != -1){
scanf("%s", &f);}
if (number !=-1)
{
pList = Addrear( pList, number, f );

}
}
printf("items in linked list \n");
PrintList ( pList );
system("PAUSE");
return 1;
}
struct node* Addrear(struct node *list, int d, char f) {
struct node *pNew = NULL;
struct node *current = NULL;
pNew = (struct node*)malloc(sizeof(struct node));
pNew ->data = d;
pNew-> fun = f;
pNew ->next = NULL;
// Store front of the linked list
current = list;
// if list is empty then this becomes the first node.
if (list == NULL)
return pNew;
while (current ->next != NULL)
current = current ->next;
current ->next = pNew;
// Return a pointer to the created list.
return list;
}
void PrintList( struct node *list)
{
struct node *current = list ;
while (current != NULL)
{
printf("--%d, %s", current -> data, current->fun);
current = current -> next;
}
printf("\n");
}

I think I might have gotten lost in my recursive function.

Alicia-chan
September 19th, 2008, 05:45 PM
I had to write a lot of these linked/dynamic structures in my data structures class (list, stack, queue, etc). It was in C++, which I'm more familiar with, so I may not be of much help.

The one thing I noticed is you are placing strings in the linked list. Since C had no explicit string type, they are stored as character arrays. So first, "char fun;", should be an array of a specified size, say 30 characters, which is then "char fun[100];" and the input would become "scanf("%s", fun);". Also, in scanf(), %s will stop at the first whitespace when you input a string (this may or may not be important). In the case of size 30 strings you could use %29s in place of %s, to take the first 29 characters input into the string.

One suggestion, it is possible to add elements to the list in an easier fashion without the while loop in your Addrear() function by organizing your list differently. Lastly, you might consider writing this in C++ (assuming pure C isn't necessary/required). You would have the string type at your disposal as well as the capability to write classes to contain your linked list and operations performed on the lists.