473,881 Members | 1,545 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why doesn't this modify the pointer?

I guess this is a kind of newbie question (since most pointer questions are
newbie questions).

In the program below, modify(string* s) is supposed to change the content
that s points to. But the main() function shows that nothing is changed at
all!

What am I doing wrong?

#include <iostream>
#include <vector>
using namespace std;

class Modifier{
private:
vector<string> newStrings;
public:
void modify(string* s){
string newString = "test"; // toy example,
// could be *s transformed into upper case etc.
newStrings.push _back(newString );
s = &(newStrings[newStrings.size () - 1]); // point to new string
}
};

int main(){
Modifier m;
string s = "Hello World";
m.modify(&s);
cout << s << endl; // should be "test", but is still "Hello World"
return(EXIT_SUC CESS);
}
Jul 23 '05 #1
4 1760
Markus Dehmann wrote:
In the program below, modify(string* s) is supposed to change the content
that s points to. But the main() function shows that nothing is changed at
all!
That's because you don't change it.
void modify(string* s){
This function gets the pointer to the string by value.
s = &(newStrings[newStrings.size () - 1]); // point to new string


This does exactly what you say. It makes the local variable s point to the
new string, it has no affect on the value in the calling function (main).

It's unclear what you want to do here. If you want to assign the value of
the new string into the old string in the parent you can do:

*s = newString;

Which chages what s points to (that is, the string called s in the parent).

You'll have to give us a more concise description of what you are trying to accomplish.
Jul 23 '05 #2
Ron Natalie wrote:
Markus Dehmann wrote:
In the program below, modify(string* s) is supposed to change the content
that s points to. But the main() function shows that nothing is changed
at all!


That's because you don't change it.
void modify(string* s){


This function gets the pointer to the string by value.
s = &(newStrings[newStrings.size () - 1]); // point to new string


This does exactly what you say. It makes the local variable s point to
the new string, it has no affect on the value in the calling function
(main).

It's unclear what you want to do here. If you want to assign the value
of the new string into the old string in the parent you can do:

*s = newString;


That works. The *s instead of s does the trick.

I'm surprised though, that this is valid code. I thought newString will be
destroyed at the end of the modify function:

void modify(string* s){
string newString = "test";
*s = newString;
}

It goes out of scope. So, if I say *s=newString, and access s later, from
the main() function, isn't that undefined behavior, because s points to
someting that has gone out of scope?

(I was using the weird vector (newStrings) strategy in order to avoid that,
but it seems that's not necessary?)

Thanks
Markus

Jul 23 '05 #3
"Markus Dehmann" <ma************ @gmail.com> wrote...
Ron Natalie wrote:
Markus Dehmann wrote:
In the program below, modify(string* s) is supposed to change the
content
that s points to. But the main() function shows that nothing is changed
at all!
That's because you don't change it.
void modify(string* s){


This function gets the pointer to the string by value.
s = &(newStrings[newStrings.size () - 1]); // point to new string


This does exactly what you say. It makes the local variable s point to
the new string, it has no affect on the value in the calling function
(main).

It's unclear what you want to do here. If you want to assign the value
of the new string into the old string in the parent you can do:

*s = newString;


That works. The *s instead of s does the trick.

I'm surprised though, that this is valid code. I thought newString will be
destroyed at the end of the modify function:

void modify(string* s){
string newString = "test";
*s = newString;
}

It goes out of scope. So, if I say *s=newString, and access s later, from
the main() function, isn't that undefined behavior, because s points to
someting that has gone out of scope?


The 'newString' does go out of scope. However, before it dies, its *value*
is _copied_ into the object pointed to by 's'. So, when the original object
goes out of scope and is destroyed, a copy of its value lives on.
(I was using the weird vector (newStrings) strategy in order to avoid
that,
but it seems that's not necessary?)


Probably. I can't say I know what you mean by "vector strategy", but it
sounds that it wasn't necessary if you can achieve the same thing through
simple copy-assignment.

V
Jul 23 '05 #4
Markus Dehmann wrote:
It's unclear what you want to do here. If you want to assign the value
of the new string into the old string in the parent you can do:

*s = newString;
That works. The *s instead of s does the trick.


Yep.
But your further reply shows that you haven't understood what it does.

's' is a pointer to a string.
This pointer is passed from main, and points to the string 'main::s'
(That is variable s in main).

'*s' dereferences that pointer and thus you get a hand on the string
object itself.

*s = That string object (the one in main, because this is where this
pointer points to) gets a new value.

*s = newString; In particular it gets a copy of the value in newString

I'm surprised though, that this is valid code. I thought newString will be
destroyed at the end of the modify function:

void modify(string* s){
string newString = "test";
*s = newString;
}

It goes out of scope.
It doesn't matter.
When newString runs out of scope, its value has long been copied to the string
object where s points to (and that is the string variable s in main).
So, if I say *s=newString, and access s later, from
the main() function, isn't that undefined behavior, because s points to
someting that has gone out of scope?


In that function, s always points to the same memory object. And that is the
variable s in main(). It never points to something else.

When you say:
*s = ...
you are changing the object where s points to. You are not changing where
s points to. If you want to change where s (the pointer in modify()) points
to you simply would do
s = ...

(But note: 's' in modify() is a local variable, so changing where this pointer
points to has no effect on the caller)

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #5

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

Similar topics

20
2119
by: CoolPint | last post by:
While I was reading about const_cast, I got curious and wanted to know if I could modify a constant variable through a pointer which has been "const_cast"ed. Since the pointer would be pointing to the constant variable and if I changed the value through the pointer, the constant variable should have been modified. Well, that's what I thought until I wrote the following and run it. #include <iostream> using std::cout; using std::endl;
3
2817
by: Shi Jin | last post by:
Hi there, I am now having a puzzle regarding what a function call actually does when called. I have a simple code to see what's going on. It is simply calling another simple function from main(). The disassembled code for the function under linux (with gcc) looks like this: pushl %ebp ;push old %ebp movl %esp, %ebp ;make new stack frame
28
12645
by: Charles Sullivan | last post by:
I'm working on a program which has a "tree" of command line arguments, i.e., myprogram level1 ]] such that there can be more than one level2 argument for each level1 argument and more than one level3 argument for each level2 argument, etc. Suppose I code it similar to this fragment: int main( int argc, char *argv ) {
13
2523
by: baumann.Pan | last post by:
when define char *p = " can not modify"; p ='b' ;is not allowed, but if you declare p as char p = "can modify"; p = 'b'; is ok? why?
12
2376
by: Michael B Allen | last post by:
Is it legit to modify static data like the following code? #include <stdlib.h> #include <stdio.h> struct tbl { int i; char *s; };
14
1491
by: grocery_stocker | last post by:
If go like the following: #include <stdlib.h> void *test_me(int a) { int *m; m = &a; } main(void){
6
7881
by: Kiran | last post by:
Hi all, What I am trying to do is to pass a pointer to the first element of an array to a function, modify it in that function, and then print out the values of the array (which has been modified by the function) in main. However, I am getting a segmentation fault. Here is the code: (Please note, the size is fixed in this code, but in my code where I am actually going to use this, the size of the array is not known until you get to the...
17
4115
by: Michael Reichenbach | last post by:
Here is the example code. int main(int argc, char *argv) { string Result; WIN32_FIND_DATA daten; HANDLE h = FindFirstFile(TEXT("c://test"), &daten); system("PAUSE"); return EXIT_SUCCESS; }
3
1953
by: TonyJ | last post by:
Hello! I supposed to modify some text files. In the file(s) which consist of different section. In one section you might have Path = <Installation_path>. The program will then replace the text string Installation_path with the path that was chosen in the installation program. An example could be this string <Installation_pathwould be replaced with this path string C:\Work\PK\Program\Test\ Now to my question is it possible to set the...
0
9776
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
10716
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
10812
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
10400
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...
1
7953
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
5780
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5976
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
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.