Shaytan
Shaytan

Reputation: 23

Passing "*&" parameters to a function

I got a function (practice for college) that I'm supposed to define, goes like this:

void add_str(char* &a, char* b);

It's supposed to add the second string to the first one. Why would I pass a *& parameter to a function, and when is it useful?

Upvotes: 1

Views: 88

Answers (2)

Edward Strange
Edward Strange

Reputation: 40859

Because you're going to need to create new space to hold the concatinated string and you need to pass that back somehow. This signature allows the function to overwrite the parameter passed in so that the pointer the caller gave will be moved to point at the new string.

This is a really, really stupid way to solve the problem but the teacher is probably trying to make some sort of point. Hopefully it's a good one. I'm not fond of broken examples but it can be hard to think of legitimate ones when what you want to teach is more usually found in something too complex to relate to newbs.

Upvotes: 2

Alan Stokes
Alan Stokes

Reputation: 18964

It allows add_str to modify whatever is passed as a. That's what a non-const reference parameter is for; it only looks odd because the parameter is a pointer rather than a simple type.

Upvotes: 1

Related Questions