Jump to content
  • Advertisement
Sign in to follow this  
kaalen

help on linked list example

This topic is 4812 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all! I'm quite new to programming... well, I have to learn it for my exam (which is tommorow by the way). I tried to do an exercise on linked list... but I've been sitting behind my desk for a few hours now and still didn't find out what the heck is wrong with my code. So here it is:
#include <stdio.h>
//definiram strukturo node (vozel)
struct node
{
	int amount;
	struct node *next;
	char *title;
};

//prototipi funkcij
struct node *add(struct node*);
struct node *display(struct node*);


int main(int argc, char *argv[])
{
	struct node *head;
	head->title="test";
	head->amount=5;
	add(head);
	return 0;
}

//funkcija za izpis seznama zaloge
struct node *display(struct node *head)
{
	printf("\nIZPIS SEZNAMA ZALOGE:\n");
	struct node *z;
	z = head;
	while(z != NULL)
	{
		printf("%d....Title: %s \t Amount: %d\n", z->title, z->amount);
		z = z->next;
	}
	printf("\n\n");
	return head;
}

//funkcija za dodajanje elementa na konec linked lista
struct node *add(struct node *head)
{
	struct node *new, *first;
	printf("Title: ");
	scanf("%s", new->title);
	//scanf("%s", &new->title);		I tried this as well but it didn't seem to help
	printf("Amount: ", new->amount);
	first = head;
	while(head->next != NULL)
	{
		head = head->next;
	}
	head->next = new;
	return first;
}
The program compiles but when I try to run it I get segmentation fault right after I type the first title... so there must be some problem with assigning the string value to title member of node structure I guess. Any idea on what is wrong? I tried to help myself with a whole bunch of literature but I didn't find any example with assigning array of characters to a member of a structure. I hope you don't get scared by this code... I guess it should be fairly simple.

Share this post


Link to post
Share on other sites
Advertisement
thank you so much... that helped instantly. I don't know why I thought I didn't have to do that. If it helps someone else to... here's the new add function:

struct node *add(struct node *head)
{
struct node *new, *first;
new = (struct node*) malloc(sizeof(struct node));
printf("Title: ");
scanf("%s", &new->title);
printf("Amount: ");
scanf("%d", &new->amount);
first = head;
while(head->next != NULL)
{
head = head->next;
}
head->next = new;
return first;
}


I guess malloc in C is something like a constructor in object oriented programming.

Share this post


Link to post
Share on other sites
The one in main needs to be malloc'd too I think. Also make sure you dont have memory leaks by using free

Share this post


Link to post
Share on other sites
ok... problems with memory allocation solved. But I still can't figure out how to read a string from stdin and assign it to the title member of node structure.

I temporarily removed title from the structure so that I could test if I'm on the right way... and my program worked fine.

I tried reading the string like this:

scanf("%s", &node->title);


but this didn't work, so I tried assigning a string from stdin to a temporary variable and then assign this variable to the title member... didn't work either. Then I tried to use strcpy function... and it didn't work.

Any idea?

Share this post


Link to post
Share on other sites
Ok, I can suggest some stuff:


#include <stdio.h>
//definiram strukturo node (vozel)
typedef struct node_t
{
int amount;
struct node *next;
char *title; //befoer this pointer can be used, it will need to be
//allocated too
} node; //now you don't have to type struct before everytime you use a node!

//prototipi funkcij
node *add(node*);
node *display(node*);


int main(int argc, char *argv[])
{
node *head; //head is a pointer, so it needs to be allocated
head = (node*)malloc(sizeof(node));
//title needs to be allocated before you can use it
head->title = (char*)malloc(sizeof(char) * (strlen("test") + 1));
strcpy(head->title, "test");
head->amount=5;
add(head);

//free memory? any pointer which has memory malloc'd to it needs to have free
//called on it before you exit, or else you will lead memory when the program
//exits

return 0;
}

//funkcija za izpis seznama zaloge
node *display(node *head)
{
node *z;
printf("\nIZPIS SEZNAMA ZALOGE:\n");
z = head;
while(z != NULL)
{
printf("%d....Title: %s \t Amount: %d\n", z->title, z->amount);
z = z->next;
}
printf("\n\n");
return head;
}

//funkcija za dodajanje elementa na konec linked lista
node *add(node *head)
{
//"new" is a restricted keyword in c++
//shouldn't be used as a variable
node *pNewNode, *first;
pNewNode = (struct node*) malloc(sizeof(struct node));
printf("Title: ");
//this char pointer needs to be allocated before you write to it
//scanf("%s", pNewNode->title);
printf("Amount: ");
scanf("%d", &pNewNode->amount);
first = head;
while(head->next != NULL)
{
head = head->next;
}
head->next = pNewNode;
return first;
}






You need to allocate the memory to that "title" char pointer before you can write any text to it.
If you look in the main function above, there's an example of how to allocate memory for char*'s. Just remember to add one to the length to accomodate the null terminator.

Edit: Also, scanf("%s", &node->title); might not work because you are trying to wriet to the address of the character pointer, not the pointer itself. You should remove the ampersand from in front of node

[Edited by - the_dannobot on September 14, 2005 12:46:31 PM]

Share this post


Link to post
Share on other sites
Quote:
I guess malloc in C is something like a constructor in object oriented programming.


Sort of. When you use a constructor in C++ for example, it sort of gets translated like this:


// C++
class Foo {
int bar;
public:
Foo() {
bar = 1; // this should go in an initializer list though :)
}
}

Foo* x = new Foo(); // notice: dynamic allocation
Foo y; // static allocation, on the stack or whatever

// becomes:

struct Foo {
int bar;
}

Foo* allocateFoo() {
return malloc(sizeof(Foo));
}

void initFoo(Foo* f) {
f->bar = 1;
}

Foo* x = allocateFoo();
initFoo(x);

Foo y;
initFoo(&y);




Quote:
Original post by kaalen
ok... problems with memory allocation solved. But I still can't figure out how to read a string from stdin and assign it to the title member of node structure.

I tried reading the string like this:

scanf("%s", &node->title);



You're close. Allocate first, and then the scanf should be ok. Except I think you need brackets: &(node->title). Otherwise it looks fine to me.

Note that the allocated space needs to be big enough for what's being read in, and you don't know ahead of time how big that is. There are generalized solutions for this that are pretty good (basically, read a character at a time and resize as you go; to make things speed-efficient, some care is needed in the resizing scheme), but they are a big headache to implement yourself - big enough that in C++, a standard library class (std::string) is provided for you to handle this stuff.

Quote:
but this didn't work, so I tried assigning a string from stdin to a temporary variable and then assign this variable to the title member... didn't work either. Then I tried to use strcpy function... and it didn't work.

Any idea?


Depending on how exactly it "doesn't work", the problem could be in different places. :/

Share this post


Link to post
Share on other sites
To allocate and read into a character string in c, you can try...

//lets the user input up to 31 characters
char strBuffer[32];
node Head;
int iStringLength;

//make sure to set stringd to 0 before you try to read into it
//otherwise it will be full of garbage
memset(strBuffer, 0, (sizeof(char) * 32));
scanf("%31s", strBuffer); //read 31 chars into buffer, not into address of buffer
iStringLength = (int)(strlen(strBuffer) + 1); //don't forget to add one for null terminator
Head.title = (char*)malloc(sizeof(char) * iStringLength); //allocate memeory for title
memset(Head.title, 0, (sizeof(char) * iStringLength));
strcpy(Head.title, strBuffer);





Normally I wouldn't hardcode a string length to 32, but I cannot find a way to set the width in scanf without using "%31s". I tried:

#define STRINGLENGTH 32
enum { STRINGLENGTH = 32 };
but niether worked correctly. Anybody have a better way?

[Edited by - the_dannobot on September 14, 2005 1:59:16 PM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!