passing char* to function

Jun 3, 2011 at 7:55pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void func(int *p)
{ 
	*p = 11;
}

void func1(char *t)
{ 
	cout<<t<<" in function\n";
	t = "new";
}

void main()
{ 
	int k=10;
	func(&k);
         cout<<k<<"\n"; 

	char *p= "old" ;
         func1(p); 
	cout<<p<<"\n";    // Why the value is "old" instead of "new"
}



why the value char *p is not changed in function body?
Jun 3, 2011 at 8:02pm
You should have const char* p = "old"; on line 18. When you assign a string literal like that, you are getting a pointer to read-only memory, which you can't modify. Or at least, modifying it has undefined behavior. In this situation, your attempt to change it is simply doing nothing.
Jun 3, 2011 at 8:06pm
This is an exact equivalent of what you are doing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
typedef char *LPSTR; //Consider LPSTR a synonym for the data type "C string".

void func(int *p)
{ 
	*p = 11;
}

void func1(LPSTR t)
{ 
	cout<<t<<" in function\n";
	t = "new";
}

void main()
{ 
	int k=10;
	func(&k);
         cout<<k<<"\n"; 

	LPSTR p= "old" ;
         func1(p); 
	cout<<p<<"\n";    // Why the value is "old" instead of "new"
}


The above should prove obvious that you did not pass a pointer to a C string. You need:

void func1(LPSTR *t)

And then call this function like this:

func1(&p);

just like you do for the other function.

EDIT: And Zhuge makes a point: Variable p is pointing to read-only characters. The appropriate declaration of p should be const char *p.
Last edited on Jun 3, 2011 at 8:08pm
Jun 3, 2011 at 8:22pm
thanks Zhuge and webjose...
Topic archived. No new replies allowed.