Moving contents of an array to another array

Sep 20, 2011 at 6:10am
Hi everyone,
I am basically going to be picking apart a c-string that contains words and putting ONLY the unique words in a 2D array of char, in such way that there will be 1 word per row in the 2D array. But how do you put the token (word) in one row of the two dimensional array?

this is what i have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
char str[101]="" ;    //This is the array where i am picking the words from
	
char twoDarray[101][16] = {}; //This is where the unique words of str are going
                          //to be placed, i unique word per row

while (!read.eof())
{
		
		read.getline(str,100,'\n');
		char *pch;
		pch = strtok (str, " , .");
		while (pch !=NULL)				
		{
			cout<<"token: "<<pch<<endl; 
			pch = strtok (NULL, " ,.");
			
			twoDarray[0][0]= pch; //*I know this part is wrong, how do you do this part??
                }
		
}


what i want to do is place the first
token from str in the first row of the twoDarray and then put second token in the next row, and so on.

Any help would be greatly appreciated.
Last edited on Sep 20, 2011 at 6:49am
Sep 21, 2011 at 1:29pm
A bi dimensional array of chars is just an unidimensional array of unidimensional arrays of chars, so each row of the first dimension is just a char* where you need to copy youtr words.

If you need to put only one instance of ech word, you could just use a map from the STL. It would take care automatically about unique words, and managing the max number of elements and max word length
Sep 21, 2011 at 1:42pm
so each row of the first dimension is just a char*


You need to copy, yeah. But it's not right to say that for this kind of 2 dimensional array each row is a char* - actually, an array declared as Type array[n][m]; Is simply treated as a Type array[n*m]; by your compiler, and accessing an index like this array[n-k][m-p] = Type(params); would be treated as array[n*(n-k)+(m-p)] = Type(params);.
Sep 21, 2011 at 1:56pm
Also, use strtok_s() if available. I still don't know if it is Microsoft-specific or not. This version is better becasue the one you use now can only parse one string at a time. What if you ever need to parse 2 strings at a time?
Topic archived. No new replies allowed.