You can do it several ways. For safety, you should add a size limit parameter so the callee (your function) knows how large the dominant dimension is:
void readNames(char names[][35], size_t n)
{
// your code here using names[0] through names[n-1]
}
and called as:
char names[20][35];
readNames(names, sizeof(names)/sizeof(*names));
Similarly, this also works (and in fact is synonymous with the above):
void readNames(char (*names)[35], size_t n)
{
// your code here using names[0] through names[n-1]
}
Both work, but there is a better way with C++ if you truly want to stick to C-style arrays. (shown later).
Lastly, this:
strcpy(userName[numberOfUsers] , userInput);
is correct syntax. Just make sure to remember that numberOfUsers
cannot exceed or meet the boundary of the array (the size_t n
you pass from the caller in the above samples). The addressing is just like C, zero based up to (n-1)
.
Fixed Array Size Determination with Template Deduction
A much more robust mechanism for doing this with C++ involves using template deduction to ensure the function knows the dimensions. It is considerably more flexible, as it can be used with different array declarations:
#include <iostream>
template<size_t N, size_t M>
void readNames(char (&names)[N][M])
{
// use names[0]... names[N-1], where
// each is a char [0..M-1] buffer.
std::cout << __PRETTY_FUNCTION__ << '\n';
}
int main()
{
char shortnames[20][30];
readNames(shortnames);
char longnames[50][100];
readNames(longnames);
return 0;
}
Output
void readNames(char (&)[N][M]) [N = 20, M = 30]
void readNames(char (&)[N][M]) [N = 50, M = 100]
How about that Standard Library, Eh?
If you really want to do the above, knock yourself out, but honestly, we're a decade-plus deep into the new millennium. Stop using technology from the 80's and 90's:
std::vector<std::string> readNames()
{
std::vector<std::string> res;
while (some-condition)
{
// get name here
std::string name;
//add to result
res.push_back(name);
}
return res;
}
Invoked like this:
std::vector<std::string> names = readNames();