You are here:

C++/Passing an array of names to a function


Hi Eddie,
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.

family.SetNames(6, *names[6])

Is the second param being passed through correctly?
Or should i have used a diff format?

Many thanks,

Followup To
Question -
Hi Eddie,
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?


Answer -
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.

- Eddie

Hello again Cruiser, thanks for the rating!

To pass that array to a function, you would pass it like any other variable:

family.SetName(6, names);

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!

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 All rights reserved.