Converting char pointer to string

Mar 5, 2013 at 4:23pm
Here's the code I'm working on:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string* arrayPush(string *array, char **toks){
    
    if(array[sizeofHistory -1].empty()){
        //find the next available element
        for(int i=0; i < sizeofHistory; i++ ){
            
            if(array[i].empty())
            {
                array[i] = *toks;
                cout << "toks: " << toks << endl;
                break;
            }
        }
    }
return array;
}


toks is an array of pointers to strings. I need to assign a toks to array[i].

I'm a c++ noob. I apologize about my ignorance in advance.
Mar 5, 2013 at 4:27pm
array[i] = toks[i];
Also, there is no need to return the pointer to the string array, it is modifying the array outside of the function.
Mar 5, 2013 at 4:33pm
toks[i] only gives me the first element. I need to get the whole array. Can I store a pointer to toks in array[i]? I will have multiple iterations through array and toks will be different each time.
Mar 5, 2013 at 4:39pm
serjo wrote:
toks[i] only gives me the first element.
What? Isn't char **toks an array of character pointers?
Mar 5, 2013 at 4:54pm
I have an array (string array[10]). On every iteration of the program (I have a while loop that calls arrayPush()) toks has different values. I find the next available element in array[] and push toks into array[i].

Later, I want to loop through the array and get toks (with all elements) on every iteration (array[i]).

in other words, toks looks something like this: **toks = {one,two,three}. If I do toks[i] it will only grab one element.

I hope this is a better explanation of the problem.
Mar 5, 2013 at 5:01pm
So, you want to have array[i] become a comma-separated list of the contents of toks?
Mar 5, 2013 at 5:05pm
I guess that could work.
Mar 5, 2013 at 5:07pm
What do you mean, you "guess that could work"? What exactly were you expecting/wanting?
Mar 5, 2013 at 5:18pm
I figured pointing to a list instead of storing it would be more efficient.
Mar 5, 2013 at 5:22pm
There are multiple problems with that. Firstly, in your original post, "array" is a pointer to string, which cannot point to a tok. Secondly, the array you would point to would need to remain valid the whole time you were working with it, which in your case may not be possible without dynamic memory (which will get messy very quickly).

Have you considered using std::vector? I highly recommend it - it manages lists of things for you and can dynamically resize by itself. In this case, "toks" would be std::vector<std::string>, and "array" would be std::vector<std::vector<std::string> >
Last edited on Mar 5, 2013 at 5:23pm
Mar 7, 2013 at 11:57pm
Topic archived. No new replies allowed.