C++/Passing an array of names to a function
I have thanked and rated you, but just want to ask one more question,
how about a function call for the below, how does it work.
Here is what i think .. but i may be wrong.
Is the second param being passed through correctly?
Or should i have used a diff format?
Just wondering how to pass this array of strings to a function. If I have an arry as follows.
char* names = [MAX_NAMES] =
How do i pass names through a function, for example, people.SetNames(numPeople, *names)
I know the above is wrong, not sure how to fix it though, any ideas?
Hello Cruiser, thank you for the question.
The declaration of that array is a tad off. It should be:
char *names[MAX_NAMES] =
// above code
In order to pass this array to a function, you pass it by pointer, since we know that the name of an array is a pointer to the first item in the array. If you pass the dereferenced name of the array, that is the first item in the array ("Anne"). The correct way to accomplish what you want it to do the following. Bear in mind the syntax may look a little odd since this is an array of pointers already:
void SetNames(unsigned int numPeople, char **names)
for(unsigned int i = 0; i < numPeople, i++)
// psuedo code: personToSet = names[i];
Another way to declare that function is like this, and it means the exact same thing:
void SetNames(unsigned int numPeople, char *names)
// above code
Either one of those declarations will work with the same code in the function. It's just a matter of personal preference. I always choose to pass arrays by pointer, but, whatever you prefer is best.
If you have any other questions, please don't hesistate to ask.
I hope this information was helpful.
Hello again Cruiser, thanks for the rating!
To pass that array to a function, you would pass it like any other variable:
The name of the array is a pointer already. Dereferencing the array name just gives you the first item in the array. The method call above is the correct syntax.
Thanks again for the rating!