Copying an array... help!

I'm writing a program that mines data from html texts files and having problems converting a list of strings to a list of ints using the function call atoi(...), which converts c style strings to ints.

Lets say I have an array of strings,length determined during compile time because we're unsure of how much data there will be in the text file.

1
2
3
4
5
6
7
8
9
10
string * list_of_strings;

list_of_strings = new string[length] //lets say length is 3, and these members are....

list_of_strings[0] = "  1";

list_of_strings[1] = "  2";

list_of_strings[2] = "  3";


for my purposes, I need to turn this array of strings to an array of integers. My array of strings could be very large, so I should use a 'for' loop for this. My question is, how do I successfully make the operation that turns each string into an integer and copy this data into a new array, then delete my old array of strings? I want to do something like....

1
2
3
4
5
6
7
8
9
10
11
12
int * list_of_ints;
int * copy;

list_of_ints = new int[length];

for(i=0; i<length; ++i) {
copy = &atoi(list_of_strings[i].c_str());

list_of_ints[i] = *copy; 
}

delete list_of_strings;


This obviously doesn't work; atoi(list_of_strings[i].c_str()) doesn't return a pointer, it returns an int. I can't use *copy = atoi(...) either because now we're dereferencing a pointer that doesn't point to anything. what is the right call here? If we simply make the call....

1
2
for(i=0; i<length; ++i)
list_of_ints[i] = atoi(list_of_strings[i].c_str());


then list_of_ints is permanently linked to the place in memory that list_of_strings is, so we we delete our strings, we get a segfault whenever we try to access anything in our list_of_ints.

I'm not sure of what to do here. A little help?

-Trent

list_of_ints is permanently linked to the place in memory that list_of_strings

Nope. Using the code you posted should work fine. atoi returns an int which you then store in your list of ints, so deleting the original strings will have no effect on that data.
Topic archived. No new replies allowed.