473,701 Members | 2,900 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 3087
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
3142
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
9926
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
3405
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
7821
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
2287
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
20401
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
9115
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
13656
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
2712
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
11095
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
8737
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9232
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...
1
8978
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
8936
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
7827
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...
1
6573
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4665
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3104
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.