473,796 Members | 2,569 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pass by Reference/value ???

hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards
Jul 22 '05 #1
14 3095
dumboo wrote:
hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
Well, the code is totally bogus and exhibits undefined behavior. If you
are lucky, it'll only crash.
void foo(char *s)
`foo()' is passed a pointer-to-char -- by value {
s = new char[10];
s -- the local copy of this pointer-to-char now points to enough memory
out of the free store to hold ten chars.
strcpy(s, "gotit");
The string literal "gotit" is copied into that memory.
}
And the local copy of `s' has gone out of scope, causing a memory leak.

int main()
{
char *s;
`s' is an uninitialized pointer-to-char that points to...well, *anywhere*,
foo(s);
`foo()' is called; however as it has been passed by value it is
unchanged, hence still uninitialized.
cout<<s;
An attempt is made to send the contents pointed to by `s' to the stream
`cout'. Since `s' points...well *anywhere*...un defined behavior is
invoked. [first time]
delete s;
An attempt to delete the memory pointed to by `s' is made. Since s is an
uninitialized pointer, undefined behavior is invoked. [second time]
return 0;
}

If you change the signature of `foo()' to:

void foo(char*& s)

you will get the behavior I would suspect you want.

HTH,
--ag
--
Artie Gold -- Austin, Texas

"Yeah. It's an urban legend. But it's a *great* urban legend!"
Jul 22 '05 #2
"dumboo" <vt***@yahoo.co m> wrote in message
news:c0******** *****@ID-211285.news.uni-berlin.de...
hi there
i m little bit confused over the following problem, i have understood wt the following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its pass by reference or pass by value...hope somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}


Here you are passing a pointer by value.

Among other things, you need to delete s like so: delete [] s.

BTW, who having you been hotly debating?

Jonathan
Jul 22 '05 #3

"Jonathan Turkanis" <te******@kanga roologic.com> wrote in message
news:c0******** *****@ID-216073.news.uni-berlin.de...

Among other things, you need to delete s like so: delete [] s.

For the 'other things' see Artie's post ;-)
Jul 22 '05 #4

"dumboo" <vt***@yahoo.co m> wrote in message
news:c0******** *****@ID-211285.news.uni-berlin.de...
hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
Didn't you try to run the program? Let's analyse the program line by line.
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s; s points to some garbage address. foo(s); Copy the garbage address contained in s to foo's s. This is pass-by-value.
Then in foo you make foo's copy of s to point to some valid dynamic store (heap)
address. Write something to it and then do a *memory leak* when you don't delete
what s points to. s gets destructed when function returns and the memory it
allocated is
never given back to the system. cout<<s; Now you return in main. Here s still points to the same garbage address it
pointed to before it entered foo.
You know now what you can expect from this program..right?
delete s; Now you try to free the memory pointed by s. But actaully s points to some
garbage address!
Also you should have done delete [] s;
return 0;
}


The easiest way to resolve this is by changing foo like -
void foo(char *& s)
Now when you change s within foo it gets reflected in main too.
This is pass-by-reference.

-Sharad
Jul 22 '05 #5
"dumboo" <vt***@yahoo.co m> wrote in message
news:c0******** *****@ID-211285.news.uni-berlin.de
hi there
i m little bit confused over the following problem, i have understood
wt the following code is doing...but not able to get the actual
techinical stuff.....i have had a lot of hot debate over the
following code whether its pass by reference or pass by value...hope
somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards

There is some confusion here resulting from C++'s origin in C. The C
language does not have C++-style references. Accordingly, if you want a
function in C to modify something, you need to pass it a pointer to the
thing to be modified. In C, this is called "passing by reference". Now
consider your function:

void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

In C, this would be called "passing by reference". The important thing to
note, however, is that the thing that is passed by reference is *not* the
variable s but what s points to, i.e., s is passed by value and what s
points to is passed by reference. What this means is that

1. foo receives a local copy of s and any changes that it makes to s only
affect that local copy.
2. the copy of s that foo receives points to the same memory area as the
original s did, so any changes made to what s points to have the same effect
within the function as they would have in the place from which the function
is called.

In your line:

s = new char[10];

you are changing the local copy of s, which has no effect on the original s.
Thus cout in main() is being applied to the uninitialised s.

If you want to modify s, then there are two ways to go about it. The C-style
approach is to pass the address of s rather than s itself, as follows:

void foo(char **ps)
{
*ps = new char[10];
strcpy(*ps, "gotit");
}

int main()
{
char *s;
foo(&s);
cout << s;
delete[] s;
return 0;
}

Note:

1. Since s is a pointer, a variable storing the address of s is a pointer to
pointer. Thus there is a double asterisk in the definition of foo's
parameter. ps is a pointer to s, so *ps gives the original s. Hence *ps
replaces s in your foo function.
2. foo is called with an argument of &s rather than with an argument of s.
3. I have changed your original delete to the (correct) array form of
delete[].

The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}
int main()
{
char *s;
foo(s);
cout << s;
delete[] s;
return 0;
}

This involves the least change to your code. All you need to do is replace

void foo(char *s)

with

void foo(char *& s)

i.e., you only need add the & symbol. This change means that s itself ---
and not just what it points to --- is "passed by reference" (in the C++
sense of that term). This means that foo operates on the original s --- no
local copy is made --- so that any changes that foo makes to s affect the
original.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)

Jul 22 '05 #6
hi there,
BTW, who having you been hotly debating?


hes my friend...studen t like me.. :-)
Jul 22 '05 #7
hi there,

"John Carson" <do***********@ datafast.net.au > wrote in message
news:40******@u senet.per.parad ox.net.au...
"dumboo" <vt***@yahoo.co m> wrote in message
news:c0******** *****@ID-211285.news.uni-berlin.de
hi there
i m little bit confused over the following problem, i have understood
wt the following code is doing...but not able to get the actual
techinical stuff.....i have had a lot of hot debate over the
following code whether its pass by reference or pass by value...hope
somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards

There is some confusion here resulting from C++'s origin in C. The C
language does not have C++-style references. Accordingly, if you want a
function in C to modify something, you need to pass it a pointer to the
thing to be modified. In C, this is called "passing by reference". Now
consider your function:

void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

In C, this would be called "passing by reference". The important thing to
note, however, is that the thing that is passed by reference is *not* the
variable s but what s points to, i.e., s is passed by value and what s
points to is passed by reference. What this means is that

1. foo receives a local copy of s and any changes that it makes to s only
affect that local copy.
2. the copy of s that foo receives points to the same memory area as the
original s did, so any changes made to what s points to have the same

effect within the function as they would have in the place from which the function is called.

In your line:

s = new char[10];

you are changing the local copy of s, which has no effect on the original s. Thus cout in main() is being applied to the uninitialised s.

If you want to modify s, then there are two ways to go about it. The C-style approach is to pass the address of s rather than s itself, as follows:

void foo(char **ps)
{
*ps = new char[10];
strcpy(*ps, "gotit");
}

int main()
{
char *s;
foo(&s);
cout << s;
delete[] s;
return 0;
}

Note:

1. Since s is a pointer, a variable storing the address of s is a pointer to pointer. Thus there is a double asterisk in the definition of foo's
parameter. ps is a pointer to s, so *ps gives the original s. Hence *ps
replaces s in your foo function.
2. foo is called with an argument of &s rather than with an argument of s.
3. I have changed your original delete to the (correct) array form of
delete[].

The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}
int main()
{
char *s;
foo(s);
cout << s;
delete[] s;
return 0;
}

This involves the least change to your code. All you need to do is replace

void foo(char *s)

with

void foo(char *& s)

i.e., you only need add the & symbol. This change means that s itself ---
and not just what it points to --- is "passed by reference" (in the C++
sense of that term). This means that foo operates on the original s --- no
local copy is made --- so that any changes that foo makes to s affect the
original.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)


thanks all the guys for the superb answer, got many of my concepts cleared
:-)
Jul 22 '05 #8
In article <40******@usene t.per.paradox.n et.au>,
John Carson <do***********@ datafast.net.au > wrote:

The C++-style approach is to use references as follows:

void foo(char *& s)
{
s = new char[10];
strcpy(s, "gotit");
}
int main()
{
char *s;
foo(s);
cout << s;
delete[] s;
return 0;
}


Or better yet, use C++'s standard 'string' data type. Then you don't have
to bother with char pointers and new and delete at all.

#include <iostream>
#include <string>

using namespace std;

void foo (string& s)
{
s = "gotit";
}

int main ()
{
string s;
foo (s);
cout << s;
return 0;
}

--
Jon Bell <jt*******@pres by.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 22 '05 #9
I will like to say that references were introduced in c++ and the
prototype of the function u have given has been there since c. and the
prototype for with pass by reference is:
void foo(char *&s)
in above prototype s is passsed by refernece parameter.
regards

"dumboo" <vt***@yahoo.co m> wrote in message news:<c0******* ******@ID-211285.news.uni-berlin.de>...
hi there
i m little bit confused over the following problem, i have understood wt the
following code is doing...but not able to get the actual techinical
stuff.....i have had a lot of hot debate over the following code whether its
pass by reference or pass by value...hope somebody clears it up :-)
void foo(char *s)
{
s = new char[10];
strcpy(s, "gotit");
}

int main()
{
char *s;
foo(s);
cout<<s;
delete s;

return 0;
}

regards

Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3151
by: Seeker | last post by:
Newbie question here... I have a form with some radio buttons. To verify that at least one of the buttons was chosen I use the following code ("f" is my form object) : var btnChosen; for (count = 0; count <= 1; count++) { if (eval(f.RadioButtons.checked)) { btnChosen = true; }
110
9969
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object must be an object instead of
4
3410
by: z_learning_tester | last post by:
I'm reading the MS press C# book and there seems to be a contradiction. Please tell me which one is correct, 1 or 2. Thanks! Jeff 1. First it gives the code below saying that it prints 0 then 42. They say that 42 is printed the second time since the value was wrapped in a class and therefore became passed by reference. (sorry for any typos I am a newbie here ;-)
5
7823
by: David++ | last post by:
Hi folks, I would be interested to hear peoples views on whether or not 'pass by reference' is allowed when using a Web Service method. The thing that troubles me about pass-by-reference into a WebService is that essentially we are passing an address of an object which resides on the 'local machine' i.e. a local machine object address. Surely when the WebService method is called and run 'on the server', the reference type will be...
4
2293
by: Jon Slaughter | last post by:
I'm reading a book on C# and it says there are 4 ways of passing types: 1. Pass value type by value 2. Pass value type by reference 3. Pass reference by value 4. Pass reference by reference. My interpretation: 1. Essentially pushes the value type on the stack
14
20414
by: Abhi | last post by:
I wrote a function foo(int arr) and its prototype is declared as foo(int arr); I modify the values of the array in the function and the values are getting modified in the main array which is passed also. I understand that this way of passing the array is by value and if the prototype is declared as foo(int *), it is by reference in which case the value if modified in the function will get reflected in the main function as well. I dont...
4
9122
by: kinaxx | last post by:
Hello, now I'm learning progamming language in university. but i have some question. in textbook. says there are four passing Mechanism 1) pass by value (inother words : call by value) 2) pass by reference (inother words: call by reference) 3) pass by value-result <- i have question this subject . 4) pass by name
10
13665
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the function is also modified. Sometimes I wish to work with "copies", in that when I pass in an integer variable into a function, I want the function to be modifying a COPY, not the reference. Is this possible?
6
2714
by: lisp9000 | last post by:
I've read that C allows two ways to pass information between functions: o Pass by Value o Pass by Reference I was talking to some C programmers and they told me there is no such thing as pass by reference in C since you are just passing an address (or a pointer value address I guess?). So I was wondering is this correct?
12
11115
by: raylopez99 | last post by:
Keywords: scope resolution, passing classes between parent and child forms, parameter constructor method, normal constructor, default constructor, forward reference, sharing classes between forms. Here is a newbie mistake that I found myself doing (as a newbie), and that even a master programmer, the guru of this forum, Jon Skeet, missed! (He knows this I'm sure, but just didn't think this was my problem; LOL, I am needling him) If...
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10455
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10228
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10173
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10006
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6788
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.