>>list is supposed to be an array of pointers, so hopefully I declared that correctly.
No, you did not declare it correctly. What you declared was an array of characters. Here is an array of pointers: char *list[LIST_SIZE];
If you want each line of the file to be in the array
string line;
int count = 0;
while( getline(infile, line) )
{
list[count] = strdup(line.c_str());
++count;
}
Since this is c++, not C, it would be even easier to use an array of std::string's or a std::vector
string list[LIST_MAX];
string line;
int count = 0;
while( getline(infile, line) )
{
list[count] = line;
++count;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Without vectors, I need it to be a dynamic array using new. So would it be:
char **list = new char[LIST_SIZE];
or char **list = new *char[LIST_SIZE];
If this is true then I would need to have my function return char **read_line , correct?
Is list type char* or type char** ? You have this in your code:
char *list = new char[LIST_SIZE];
That would make list type char*. If list is to be an array of pointers, it should be type char**. If list is type char**, both of these would be incorrect:
char **list = new char[LIST_SIZE];
char **list = new *char[LIST_SIZE];
This would be correct:
char **list = new char*[LIST_SIZE];
Then if you wanted to have each char* be a character array, you could now set aside space using new again:
char **list = new char*[LIST_SIZE];
for (int i = 0; i < LIST_SIZE; i++)
{
list[i] = new char[50];
}
This is assuming you want an array of LIST_SIZE C-Style strings, each array element having a capacity of 50 characters.
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
Here's a sample program that may be useful:
#include <iostream>
using namespace std;
int main()
{
int LIST_SIZE, NUM_CHARS_PER_ELEMENT;
cout << "Enter number of elements in list: ";
cin >> LIST_SIZE;
cout << "Enter number of characters in each array element: ";
cin >> NUM_CHARS_PER_ELEMENT;
char **list = new char*[LIST_SIZE];
for (int i = 0; i < LIST_SIZE; i++)
{
list[i] = new char[NUM_CHARS_PER_ELEMENT];
}
cout << "Enter " << LIST_SIZE << " names\n";
for (int i = 0; i < LIST_SIZE; i++)
{
cout << "Enter name " << i << " : ";
cin >> list[i];
}
cout << "Here are the names\n";
for (int i = 0; i < LIST_SIZE; i++)
{
cout << "Name " << i << " : " << list[i] << endl;
}
return 0;
}
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711