You are here:

C++/string pointer

Advertisement


Question
Why does the following program not change the value of p after invoking the function 'st'?

#include <iostream.h>
#include <conio.h>
void st(char * q)
{
q = "xyz";
cout<<q;
}
void main()
{
char *p;
p = "abc";
st(p);
cout<<p;
}

The output expected is :  xyzxyz
but Actual output is   :  xyzabc

Pl. Send us a reply explaining the reson for the output.

Thanks.


Answer
Psbb,
It has been awhile since I've worked with pointers, so I'm not sure my advice will work, but it's the only explanation I can think of. From what I can tell though, your functino is a call by value and not a call by reference. You're sending the variable 'p' to the 'st' function, but the 'st' function doesn't actually change the value of 'p'. The value of 'p' in the main portion of the program remains constant. So just change the function to a call by reference and you should be set.

Best Of Luck,
Alan

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Alan F.

Expertise

Having problems with any basic or intermediate parts of C++? I can answer those questions for you using simple English. I have been taking C++ in school for a couple years, so I still remember what it was like to be a beginner (especially with C++, which is a difficult language)!

Experience

I have a C++ web page that discuses the basics of C++. The address is: http://www.afweb.net/complang/

©2016 About.com. All rights reserved.