Sign in to follow this  
DarkThrone

Some help with linked lists.

Recommended Posts

DarkThrone    100
I use this function above to same a linked list word spliter. I don't know why, but it allocs only a limited range of words(between 10 and 20). Can anybody help? void WordList::SplitWordsOntoList(char *st, char delimiter, char lastchar) { unsigned int position = 0; char buffer[50]; unsigned int arraylenght = 0; for(position = 0;position < 50; position++) { if(st[position] != delimiter && st[position] != lastchar) { buffer[arraylenght] = st[position]; arraylenght++; } else { buffer[arraylenght] = '\0'; pttabpos->word = strdup(buffer); pttabpos->nextWord = new WordTable; pttabpos = pttabpos->nextWord; pttabpos->nextWord = NULL; arraylenght = 0; if(st[position] == lastchar) { return; } } } }

Share this post


Link to post
Share on other sites
jyk    2094
You're only looping 'position' from 0 to 50 (presumably because that's the size of your buffer). I think you want to loop until the last character is reached.

(There could be other things as well, but I didn't look at it too carefully...)

Share this post


Link to post
Share on other sites
Zahlman    1682
Dear god.

The standard library provides everything you need here.


#include <list>
#include <string>
#include <sstream>
#include <iostream>

typedef std::list<std::string> WordList;

// This could easily be wrapped in an OO style instead. But be sure to
// include a std::list<std::string> as a data member in that case, and do *not*
// inherit from that class - it's not designed for inheritance.
void appendWordsTo(WordList& target, const std::string& wordSource) {
std::stringstream ss(wordSource);
std::string word;
while (ss >> word) { target.push_back(word); }
}

int main() {
WordList tmp;
appendWordsTo(tmp, "I liek pie");
for (WordList::iterator it = tmp.begin(); it != tmp.end(); ++it) {
std::cout << *it << std::endl;
}
}



This works for any number of words, of any length (subject to limitations on available memory), without allocating huge buffers (unless they happen to be necessary) - and also will get all the memory allocation/deallocation correct, without leaks, double deletes or any other such nonsense. Plus it's straightforward. :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this