How to split a string into a linked list? (C++ question)
My first post~~!!! Ahem... but i digress...
I'm writing a simple text editor and I've run into a little problem. The function will receive a string (in form of const void*) and must separate the string by new lines. An example string that will be passed up is this: Code:
char* example = So this is what I have so far: Code:
void IO_TextEdit::set(const void *str) { So, if I passed a string that contains 3 lines overall, the linked list will contain 3 nodes containing only the last line of the string passed. I know my solution lies with pre-allocating memory, but I'm not exactly sure how I can do this. I've tried using malloc(), but I'm not quite sure if I'm using it correctly. Sorry if this was lengthy, but I wanted to be as descriptive as possible. Any help would be highly appreciated! |
Looks more like C than C++!
The C++ way would be to store the strings as std::strings and use a std::vector<std::string> to store the split ones, rather than operating on a low level of pointers and linked lists. See sector 7.3 here: http://www.oopweb.com/CPP/Documents/...g-HOWTO-7.html |
Yes, there is a some confusion in the code.
You are allocating space for a temp string at the start, but then overwriting the pointer (which will cause a memory leak). Code:
char* temp = new char[strlen((char *)str)]; Code:
char lineHolder[_IO_TEXT_ALLOCATION_LINE_SIZE]; Instead, use the new[] to allocate the lineHolder buffer each time around the loop (after calculating the size), so that each line buffer is on the heap. Code:
char *lineHolder = new char[i-k+1]; If you intend to write a significant amount of C++ code, it is worth also being aware of the boost libraries, which can handle some of these basic algorithms. For example, splitting up the string into a list container becomes: Code:
#include <string> |
Funny thing is, I actually started with new[].. I can't remember, but I think my problem was actually how I organized it... i think i did something like:
Code:
set() { |
All times are GMT -5. The time now is 05:34 AM. |