Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C++ amatuer needs help with arrays!

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Okay, arrays are passed by reference...

So, when I pass the array into a function, and inside
that function, i change the value of the array, now when
i return back to its caller, the value is NOT changed? why?
pass by reference are suppose to change it right?
For example...

void doit(char* msg)
{
msg = "Hi";
}

void main()
{
char* msg = "Hello World!";

doit(msg);
<---- at this point, msg is STILL &quot;Hello World!&quot;

printf(&quot;%s\n&quot;, msg);
}

WHY? Isnt pass by reference suppose to change msg to &quot;Hi&quot; instead? If not? How do I pass array by reference and CHANGE the value?

I tried using all sorts of functions like memcpy(),
memmove(), strcpy(), etc, and NONE work.

So does anyone know how can i TRUELY pass an array by
reference? I need the value to change and return it back.
(And no, i wish to avoid using a return statement by returning a char*, I want to return by ref)

Thank you.
 
NO. That wont work. you cant set a char array by

msg = &quot;Hi&quot;

you need to use

strcpy, sprintf or other string functions.

Ex.

strcyp(msg,&quot;Hi&quot;);

That will do it for you. By passing it as a pointer you are passing it by reference.

matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top