Re: Array of Strings in C++
Are you really sure you want to do that? This would be a lot easier to do with a vector of real honest-to-gosh C++ style strings. Then you don't have to mess with pointers, which are easy to make mistakes with (as I'm sure you're aware )
Code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// pass the vector of strings by reference (note the &)
// so no copying is needed
void Display (const vector<string>& v)
{
// Vectors "know" how big they are, so you don't have to
// pass the size separately.
for (int k = 0; k < v.size(); ++k)
{
cout << "String #" << k << ": " << v[k] << endl;
}
}
int main ()
{
// Create this vector with a specific size
vector<string> myStrings(7);
// Each string automatically expands to accommodate its characters
myStrings[0] = "Hi";
myStrings[1] = "I";
myStrings[2] = "am";
myStrings[3] = "a";
myStrings[4] = "vector";
myStrings[5] = "of";
myStrings[6] = "strings";
Display (myStrings);
// Create this vector with size zero, and let it grow to
// accommodate the data
vector<string> moreStrings;
moreStrings.push_back("I");
moreStrings.push_back("am");
moreStrings.push_back("another");
moreStrings.push_back("vector");
Display (moreStrings);
return 0;
}
You can use pointers to pass data to functions in C++, but I personally
prefer to use references, as in the example above.
Re: Array of Strings in C++
You can do it in the most obvious way. Here is some code:
Code:
void print_strings(const char *arr[], const int arr_sz)
{
for (int i=0; i < arr_sz; i++)
std::cout << arr[i] << std::endl;
}
const int arr_sz = 3;
const char *arr[sz] = { "first", "second", "third" };
print_strings(arr);
arr[0] = "first modified";
print_strings(arr);
Is this what you were looking for?
Re: Array of Strings in C++
No one has given you exactly what you have asked for so here it is, it might
be what you want, but I doubt it.
Code:
void func(char* (&array)[3]);
int main()
{
char* array[3] = { "apple", "pear", "orange" };
func(array);
}
void func(char* (&array)[3])
{
for (int i = 0; i < 3; ++i)
cout << array[i] << '\n';
}
The strange syntax for the parameter of func is how you pass an array by
reference.