You are here:

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

Advertisement


Question
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.
eg.

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

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

Many thanks,
Cruiser.






-------------------------
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] =
{
 ("Anne"),
 ("Barry"),
 ("Colum")
};

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?


Thanks,
Cruiser

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

Answer
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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

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 ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

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 About.com. All rights reserved.