-
question
i have a question......i have a program that i am using two dimensional arrays to store words. for example for an array[10][10], the first subscript will contain a word and the second subscript will contain the characters of trhe word. i have decided that i would rather be using a linked list instead of an array, is there any way to take the words stored in each subscript and put them into one place in a linked list. here is some example code that i came up with trying to do this.
#include <iostream.h>
#include <fstream.h>
#include <string>
struct StackFrame
{
char data;
StackFrame *link;
};
typedef StackFrame* StackFramePtr;
void main()
{
char array[1][5];
array[0][0] = 'h';
array[0][1] = 'e';
array[0][2] = 'l';
array[0][3] = 'l';
array[0][4] = 'o';
StackFramePtr top;
top = new StackFrame;
top->data = array[0];
top->link = NULL;
cout << top->data;
}
-
Quote:
Code:
struct StackFrame
{
char data;
StackFrame *link;
};
you can use a string object as a data member of your node to store each word.
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
str = "hello";
cout << str << endl;
return 0;
}
Or you can dynamically or statically allocate an array for each word and use strcpy to copy the word over
Code:
#include <iostream>
using namespace std;
int main()
{
char str1[10];
strcpy(str1, "hello");
cout << str1 << endl;
return 0;
}
one of these two options will work
-
I'd suggest you store one string per node instead of a single character.
Code:
typedef struct _NODE
{
char* Word;
struct _NODE* NextNode;
}NODE;
-
this:
top->data
is a char, whereas this:
array[0];
is an array, and maybe a string--if it is null terminated. Therefore this:
top->data = array[0];
is attempting to assign an array to a char. Won't work.
Using your schema it should be this:
top->data = array[0][0];
Note: this:
char words[x][y];
is an array of x words each of which can have up to y char (or letters) each. If you want the words to be strings, then the char immediately after the last letter of each word needs to be the null character; which means, that if words is an array of strings, then the strings can hold up to y - 1 letters, not y. In your case x is 1 and y is 5 and the array is a single array of an array of 5 char; the array of 5 char not being a string. This is legal, as long as you don't try to use the array as a string.